I just learnt how to create a GraphlQL server using graphql-yoga
and prisma-binding
based on the HowToGraphQL tutorial.
Question: The only way to query the database so far was to use the Prisma Playground webpage that was started by running the command graphql playground
.
Is it possible to perform the same query from a Node.js script? I came across the Apollo client but it seems to be meant for use from a frontend layer like React, Vue, Angular.
答案 0 :(得分:3)
这是绝对可能的,最终Prisma API只是纯HTTP,您可以在其中将查询放入POST
请求的 body 中。
因此,您也可以在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绑定的方法:
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))
答案 1 :(得分:0)
由于您正在使用Prisma,并且想从NodeJS脚本中查询它,所以我认为您可能忽略了根据Prisma定义生成客户端的选项。
它负责根据数据模型处理创建/读取/更新/删除/更新方法。 此外,由于模型和查询/变异是使用Prisma CLI(Prisma生成)生成的,因此不必担心保持同步。
与使用原始GrahQL查询相比,我发现它节省了很多编码时间,而我将其保存用于更复杂的查询/突变。
查看他们的official documentation以获得更多详细信息。
此外,请注意,在prisma-binding中使用Prisma客户端是推荐的使用Prisma的方式,除非:
除非您明确要使用架构委托
我不能告诉你很多。
直到我读完您的问题,我才知道prisma-binding
软件包。
编辑:
这是另一个link,将它们都放在了视角