【问题标题】:Apollo-server 2 validation middlewareApollo-server 2 验证中间件
【发布时间】:2019-05-19 04:37:10
【问题描述】:

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

如果不手动将其放入每个解析器函数中,我不清楚将其注入何处。

【问题讨论】:

    标签: javascript graphql apollo-server


    【解决方案1】:

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

    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
    }
    

    【讨论】:

      【解决方案2】:

      您可以在context 中添加您的验证方法,您还可以在其中获取请求参数、查询、标头等

      您还可以考虑实现可应用于架构级别的自定义指令。

      参考https://www.apollographql.com/docs/apollo-server/features/authentication.html

      【讨论】:

        猜你喜欢
        • 2019-06-08
        • 2018-05-23
        • 2020-03-19
        • 2018-08-18
        • 2019-05-02
        • 2020-05-13
        • 2018-12-14
        • 2019-01-25
        • 2020-05-28
        相关资源
        最近更新 更多