我刚刚学习了如何使用基于 the HowToGraphQL tutorial 的 graphql-yoga
和 prisma-binding
创建 GraphlQL 服务器。
问题:到目前为止,查询数据库的唯一方法是使用通过运行命令 graphql Playground
启动的 Prisma Playground 网页。
是否可以从 Node.js 脚本执行相同的查询?我遇到过 Apollo 客户端,但它似乎是为了从 React、Vue、Angular 等前端层使用而设计的。
最佳答案
这绝对是可能的,最终 Prisma API 只是普通的 HTTP,您可以将查询放入 POST
请求的正文中。
因此,您也可以在 Node 脚本中使用 fetch
或 prisma-binding
。
这也可能会有所帮助,因为它解释了如何使用 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/