Apollo-server 2 验证中间件

SIL*_*ENT 6 javascript graphql apollo-server

我想向 apollo 服务器添加一个验证层。它应该在每个 graphql 查询/突变之后但在解析器函数之前运行。验证层需要知道被调用的 graphql 查询/变异以及传递的参数。如果无效,它将抛出错误并阻止解析器功能运行。

我不清楚在哪里注入它而不手动将它放在每个解析器函数中。

Dan*_*den 4

graphql-tools实际上包含一个addSchemaLevelResolveFunction实用程序,允许您包装每个Query,MutationSubscription字段的解析器以模拟“根级解析器”:

const { makeExecutableSchema, addSchemaLevelResolveFunction } = require('graphql-tools')

const schema = makeExecutableSchema({ resolvers, typeDefs })
const rootLevelResolver = (root, args, context, info) => {
  // Your validation logic here. Throwing an error will prevent the wrapped resolver from executing.
  // Note: whatever you return here will be passed as the parent value to the wrapped resolver
}
addSchemaLevelResolveFunction(schema, rootLevelResolver)
Run Code Online (Sandbox Code Playgroud)

这是将一些逻辑应用于所有根级字段的简单方法,但如果您只想将此逻辑应用到某些字段,则会有点麻烦。如果是这种情况,现在您必须维护一个与架构分开的白名单或黑名单字段列表。如果团队中的其他人正在添加新字段并且不知道此机制,这可能会很麻烦。如果您想将相同的逻辑应用于根级别之外的字段,它也没有太大帮助。

更好的方法是使用自定义架构指令,如文档中所述。这允许您指示将逻辑应用到哪些字段:

directive @customValidation on FIELD_DEFINITION

type Query {
  someField: String @customValidation
  someOtherField: String
}
Run Code Online (Sandbox Code Playgroud)