Apollo-server 2 验证中间件
Apollo-server 2 validation middleware
我想给 apollo 服务器添加一个验证层。
它应该 运行 在每个 graphql 查询/突变之后但在解析器函数之前。验证层将需要知道被调用的 graphql 查询/突变和传递的参数。如果它无效,它将抛出一个错误并阻止解析器函数 运行ning.
如果不手动将其放置在每个解析器函数中,我不清楚将其注入何处。
you can add your validation method inside context
where you can also get request parameters, query, headers, etc
You can also consider implementing custom directive which can be applied on schema level.
ref https://www.apollographql.com/docs/apollo-server/features/authentication.html
graphql-tools
实际上包括一个 addSchemaLevelResolveFunction
实用程序,它允许您为每个 Query
、Mutation
和 Subscription
字段包装解析器以模拟 "root level resolver":
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)
这是将某些逻辑应用到所有根级字段的简单方法,但如果只有 一些 字段您想应用此逻辑,就会有点麻烦。如果是这种情况,现在您必须维护一个白名单或黑名单字段列表,与您的架构分开。如果您团队中的其他人正在添加新字段并且不知道此机制,这可能会很麻烦。如果您想将相同的逻辑应用于根级别字段之外的字段,它也不是很有帮助。
更好的方法是使用自定义架构指令,as outlined in the docs。这允许您指示将逻辑应用于哪些字段:
directive @customValidation on FIELD_DEFINITION
type Query {
someField: String @customValidation
someOtherField: String
}
我想给 apollo 服务器添加一个验证层。 它应该 运行 在每个 graphql 查询/突变之后但在解析器函数之前。验证层将需要知道被调用的 graphql 查询/突变和传递的参数。如果它无效,它将抛出一个错误并阻止解析器函数 运行ning.
如果不手动将其放置在每个解析器函数中,我不清楚将其注入何处。
you can add your validation method inside
context
where you can also get request parameters, query, headers, etcYou can also consider implementing custom directive which can be applied on schema level.
ref https://www.apollographql.com/docs/apollo-server/features/authentication.html
graphql-tools
实际上包括一个 addSchemaLevelResolveFunction
实用程序,它允许您为每个 Query
、Mutation
和 Subscription
字段包装解析器以模拟 "root level resolver":
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)
这是将某些逻辑应用到所有根级字段的简单方法,但如果只有 一些 字段您想应用此逻辑,就会有点麻烦。如果是这种情况,现在您必须维护一个白名单或黑名单字段列表,与您的架构分开。如果您团队中的其他人正在添加新字段并且不知道此机制,这可能会很麻烦。如果您想将相同的逻辑应用于根级别字段之外的字段,它也不是很有帮助。
更好的方法是使用自定义架构指令,as outlined in the docs。这允许您指示将逻辑应用于哪些字段:
directive @customValidation on FIELD_DEFINITION
type Query {
someField: String @customValidation
someOtherField: String
}