prisma middleware 简化 graphql resolver 编写的类库

时间:2023-03-08 16:44:04

prisma 推出middleware 的目的就是保持resolver 的简洁
作用:

  • 输入参数访问同一个resolver
  • 决定resolver 最终的返回值
  • 在resolver 连中捕获异常以及错误

基本项目

  • 初始化项目
yarn init -y
  • 添加依赖
yarn add graphql-yogo
  • 测试代码
const { GraphQLServer } = require('graphql-yoga')

const typeDefs = `
type Query {
hello(name: String): String
bye(name: String): String
}
`
const resolvers = {
Query: {
hello: (root, args, context, info) => {
console.log(`3. resolver: hello`)
return `Hello ${args.name ? args.name : 'world'}!`
},
bye: (root, args, context, info) => {
console.log(`3. resolver: bye`)
return `Bye ${args.name ? args.name : 'world'}!`
},
}
} const logInput = async (resolve, root, args, context, info) => {
console.log(`1. logInput: ${JSON.stringify(args)}`)
const result = await resolve(root, args, context, info)
console.log(`5. logInput`)
return result
} const logResult = async (resolve, root, args, context, info) => {
console.log(`2. logResult`)
const result = await resolve(root, args, context, info)
console.log(`4. logResult: ${JSON.stringify(result)}`)
return result
} const middlewares = [logInput, logResult] const server = new GraphQLServer({
typeDefs,
resolvers,
middlewares,
})
server.start(() => console.log('Server is running on http://localhost:4000'))

运行&&测试

  • 运行
node app
or
yarn start

prisma middleware 简化 graphql  resolver 编写的类库

  • graphql playground
    prisma middleware 简化 graphql  resolver 编写的类库
  • 访问日志
    请求内容
query {
hello(name:"dalong")
}

日志内容
prisma middleware 简化 graphql  resolver 编写的类库

处理流程

遵循的是洋葱原则,如下图,同时中间件数据的顺序比较重要,同时每个中间价包含一个before after 在实际的resolver 执行
的时候
prisma middleware 简化 graphql  resolver 编写的类库

特定query 的应用middleware

  • 参考代码
const middleware1 = {
Query: {
hello: logInput,
bye: logInput
}
} const middleware2 = {
Query: {
bye: logResult
}
} const middlewares = [middleware1, middleware2] const server = new GraphQLServer({
typeDefs,
resolvers,
middlewares,
})

与directive 的区别

中间价更灵活,同时更容易控制系统对于字段数据的处理,而指令更多的是字段、或者类似级别的,具体详细
的可以参考资料

参考资料

https://www.prisma.io/blog/graphql-middleware-zie3iphithxy/