【问题标题】:Implement custom logic after the graphql query has been parsed解析graphql查询后实现自定义逻辑
【发布时间】:2021-12-16 17:14:51
【问题描述】:

有没有办法在解析 graphql 查询之后,但在任何解析器执行之前实现自定义逻辑?

鉴于此查询架构

type Query {
  products(...): ProductConnection!
  productByHandle(handle: String!): Product
}

如何在解析器有机会执行之前完成为 productsproductByHandle 查询记录 info 对象的任务?

我基本上是想“连接”到像query:parsed 这样的虚构事件,但它似乎并不存在。我正在使用express-graphql 包。

【问题讨论】:

  • .... 中间件?
  • 我不确定你到底在说什么中间件。 Express 中间件不允许您拦截 graphql 解析,它只允许您在 graphql 端点之前/之后做一些事情,这里的要求之一是我可以访问已解析的 graphql 查询,但拦截它的执行。
  • 嗯,然后是一些选项github.com/graphql/express-graphql#options ... customExecuteFn(原始之前)或customParseFn(原始之后)?

标签: node.js express graphql


【解决方案1】:

支持@xadm 解决这个问题。

express-graphql 包接受自定义执行函数,该函数是在解析查询后调用的函数。它的返回值是从/graphql 端点返回的值。

import { graphHTTP } from 'express-graphql'
import { execute } from 'graphql'

app.use('/graphql', graphHTTP((req, res) => {
    return {
        ...,
        async customExecuteFn(ExecutionArgs) {
            // The `info` object is available on ExecutionArgs

            // { data: {...}, errors: [...] }
            const result = await execute(ExecutionArgs)

            return result
        }
    }
}))

我还是把它留在这里,因为它可能对更具体的东西有用,但你可能应该使用上面的代码。

// This returns an object, whose keys are the query names and the values are the definitions ( name, resolve etc )
const queryFields = graphqlSchema.getQueryType().getFields()

// They can then be iterated, and the original `resolve` method can be monkey-patched
for (const queryName in queryFields) {
    const queryInfo = queryFields[queryName]
    // Grab a copy of the original method
    const originalResolve = queryInfo.resolve

    // Overwrite the original `resolve` method 
    queryInfo.resolve = function patchedResolve(src, args, context, info) {
        // Your custom logic goes here
        console.log(info);

        // Call the original `resolve` method, preserving the context and
        // passing in the arguments
        return originalResolve.apply(this, arguments)
    }
}

【讨论】:

    猜你喜欢
    • 2018-03-18
    • 2018-07-19
    • 2020-07-04
    • 2015-01-01
    • 2021-05-17
    • 1970-01-01
    • 1970-01-01
    • 2021-12-22
    • 1970-01-01
    相关资源
    最近更新 更多