代码之家  ›  专栏  ›  技术社区  ›  Nyxynyx

如何将graphql查询从node.js发送到prisma

  •  2
  • Nyxynyx  · 技术社区  · 7 年前

    我刚刚学会了如何使用 graphql-yoga prisma-binding 基于 the HowToGraphQL tutorial .

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

    是否可以从node.js脚本执行相同的查询?我遇到了Apollo客户机,但它似乎是从前端层使用的,比如React、Vue、Angular。

    2 回复  |  直到 7 年前
        1
  •  3
  •   nburk    7 年前

    这是绝对可能的,最终prisma api只是一个普通的HTTP,您可以将查询放入 身体 A的 POST 请求。

    因此,您可以使用 fetch prisma-binding 也在节点脚本中。

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

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

    这就是使用 取来 看起来像:

    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)))
    

    如果你想用一个轻量级的包装 取来 这样你就不用写样板了,一定要检查一下 graphql-request .

    下面介绍如何使用prisma绑定:

    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))
    
        2
  •  0
  •   Anas Tiour    7 年前

    因为您使用的是prisma,并且希望从nodejs脚本查询它,所以我认为您可能忽略了从prisma定义生成客户机的选项。

    它负责处理创建/读取/更新/删除/更新方法,具体取决于您的数据模型。 此外,由于模型和查询/突变是使用prisma cli(prisma generate)生成的,因此您可以减少对保持模型和查询/突变同步的担忧。

    与使用原始Grahql查询相比,我发现它节省了大量的编码时间,而对于更复杂的查询/突变,我也节省了大量的编码时间。

    检查他们 official documentation 了解更多详细信息。

    另外,请注意使用prisma客户端是在 prisma-binding 可转让,除非:

    除非您明确希望使用模式委派

    我不能告诉你很多。

    我不知道 prisma-binding 打包,直到我读到你的问题。

    编辑:

    这里是另一个 link 这使他们都有了远见

    推荐文章