这绝对是可能的,最终 Prisma API 只是简单的 HTTP,您将查询放入 POST 请求的 body 中。
因此,您也可以在 Node 脚本中使用 fetch 或 prisma-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 绑定:
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))