我想向阿波罗服务器添加一个验证层。它应该在每个graphql查询/变异之后,但在解析器函数之前运行。验证层需要知道调用的graphql查询/突变以及传递的参数。如果其无效将引发错误,并阻止解析器函数运行。
我不清楚在没有手动将它放在每个解析器函数的情况下注入它的位置。
发布于 2018-12-18 18:37:05
graphql-tools实际上包括一个addSchemaLevelResolveFunction实用程序,它允许您为每个Query、Mutation和Subscription字段包装解析器,以模拟“根级解析器”:
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)这是将一些逻辑应用于所有根级字段的简单方法,但如果只有--一些字段--您想将此逻辑应用于其中,则会变得有些模糊。如果是这样的话,现在您必须维护一个从模式中分离出来的白名单或黑名单字段。如果您团队中的其他人正在添加一个新字段而不知道这个机制,这可能会很麻烦。如果您想将相同的逻辑应用于根级字段之外的字段,这也不太有帮助。
更好的方法是使用自定义模式指令如文档中所述。这允许您指示要将逻辑应用到哪些字段:
directive @customValidation on FIELD_DEFINITION
type Query {
someField: String @customValidation
someOtherField: String
}发布于 2018-12-18 18:13:31
可以在
context中添加验证方法,其中还可以获取请求参数、查询、标头等。 您还可以考虑实现可应用于架构级别的自定义指令。 参考文献https://www.apollographql.com/docs/apollo-server/features/authentication.html
https://stackoverflow.com/questions/53838475
复制相似问题