graphql - 如何将 GraphQL 查询从 Node.js 发送到 Prisma

标签 graphql apollo apollo-client prisma prisma-graphql

我刚刚学习了如何使用基于 the HowToGraphQL tutorialgraphql-yogaprisma-binding 创建 GraphlQL 服务器。

问题:到目前为止,查询数据库的唯一方法是使用通过运行命令 graphql Playground 启动的 Prisma Playground 网页。

是否可以从 Node.js 脚本执行相同的查询?我遇到过 Apollo 客户端,但它似乎是为了从 React、Vue、Angular 等前端层使用而设计的。

最佳答案

这绝对是可能的,最终 Prisma API 只是普通的 HTTP,您可以将查询放入 POST 请求的正文中。

因此,您也可以在 Node 脚本中使用 fetchprisma-binding

查看本教程以了解更多信息:https://www.prisma.io/docs/tutorials/access-prisma-from-scripts/access-prisma-from-a-node-script-using-prisma-bindings-vbadiyyee9

这也可能会有所帮助,因为它解释了如何使用 fetch 来查询 API:https://github.com/nikolasburk/gse/tree/master/3-Use-Prisma-GraphQL-API-from-Code

这就是使用fetch的样子:

const fetch = require('node-fetch')

const endpoint = '__YOUR_PRISMA_ENDPOINT__'

const query = `
query {
  users {
    id
    name
    posts {
      id
      title
    }
  }
}
`

fetch(endpoint, {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ query: query })
})
  .then(response => response.json())
  .then(result => console.log(JSON.stringify(result)))

如果您想使用 fetch 的轻量级包装器来避免编写样板文件,请务必查看 graphql-request .

以下是如何使用 Prisma 绑定(bind):

const { Prisma } = require('prisma-binding')

const prisma = new Prisma({
  typeDefs: 'prisma.graphql',
  endpoint: '__YOUR_PRISMA_ENDPOINT__'
})

// send `users` query
prisma.query.users({}, `{ id name }`)
  .then(users => console.log(users))
  .then(() =>
    // send `createUser` mutation
    prisma.mutation.createUser(
      {
        data: { name: `Sarah` },
      },
      `{ id name }`,
    ),
  )
  .then(newUser => {
    console.log(newUser)
    return newUser
  })
  .then(newUser =>
    // send `user` query
    prisma.query.user(
      {
        where: { id: newUser.id },
      },
      `{ name }`,
    ),
  )
  .then(user => console.log(user))

关于graphql - 如何将 GraphQL 查询从 Node.js 发送到 Prisma,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51510940/

相关文章:

reactjs - 使用 GraphQL 在 NextJS 中呈现比之前呈现更多的钩子(Hook)

swift - 运行脚本阶段错误 : framework is a directory

angular - "Cannot return null for non-nullable field"使用 Graphql 订阅 NestJS 时

Apollo 客户端 GraphQL 在 Next.js getStaticProps 上创建静态页面

javascript - 当没有数据返回时,GraphQL 变异返回类型应该是什么?

mysql - Apollo 服务器订阅不起作用

node.js - 为什么使用数据加载器进行批处理在测试中不起作用?

Azure Cosmos db 和函数 javascript sdk - 如何异步读取文档?

typescript - 如何在使用 Vue CLI@3 和 TypeScript 设置的项目中使用?

reactjs - 继电器现代: delete record in optimisticUpdater