繁体   English   中英

如何扩展GraphQL调用的上下文对象?

[英]How to extend the context object of a GraphQL call?

我在标准模块中有以下GraphQL服务器调用:

export default () => {
    return graphqlHTTP({
        schema: schema,
        graphiql: true,
        pretty: true,
        formatError: error => ({
            message: error.message,
            locations: error.locations,
            stack: error.stack,
            path: error.path
        })
    });
};

与护照一起使用:

app.use(
    "/graphql",
    passport.authenticate("jwt", { session: false }),
    appGraphQL()
);

一切都在工作文件中。 护照延长我的req得到那个是我GraphQL来电查询或突变使用的登录用户对象:

...
    resolve(source, args, context) {
        console.log("CURRENT USER OBJECT")
        console.log(context.user)
...

一切都很好。

现在,我需要扩展上下文以添加一些自定义解析器,因此我的第一个尝试是:

export default () => {
    return graphqlHTTP({
        schema: schema,
        graphiql: true,
        pretty: true,
        context: resolvers,
        formatError: error => ({
            message: error.message,
            locations: error.locations,
            stack: error.stack,
            path: error.path
        })
    });
};

就像GraphQL文档所说的那样,这会覆盖原始的req上下文,而我的context.user在查询和变异时会停止工作。

如何正确扩展当前上下文以添加更多字段,而不是覆盖它? 另一种不成功的尝试:

export default (req) => {
    return graphqlHTTP({
        schema: schema,
        graphiql: true,
        pretty: true,
        context: {
            user: req.user,
            resolvers: resolvers
        },
        formatError: error => ({
            message: error.message,
            locations: error.locations,
            stack: error.stack,
            path: error.path
        })
    });
};

这种方法不起作用...我收到以下错误:

  user: req.user,
                ^

TypeError: Cannot read property 'user' of undefined

[edit]我最近的尝试来自我在Apollo Docs上的示例:

export default () => {
    return graphqlHTTP({
        schema: schema,
        graphiql: true,
        pretty: true,
        context: ({ req }) => ({
            user: req.user
        }),
        formatError: error => ({
            message: error.message,
            locations: error.locations,
            stack: error.stack,
            path: error.path
        })
    });
};

现在,我的上下文是解析器中的一个函数:

console.log(context)
console.log(context.user)

返回:

[Function: context]
undefined

用这个简单的东西发疯...

假设您使用的是express-graphqlgraphqlHTTP是一个需要一些配置参数并返回一个express中间件函数的函数。 通常,它的用法如下:

app.use(
  '/graphql',
  graphqlHTTP({ ... })
)

但是,graphqlHTTP可以使用返回对象的函数来代替对象,如docs所示。

app.use(
  '/graphql',
  graphqlHTTP((req, res, graphQLParams) => {
    return { ... }
  })
)

这样,您可以在配置对象中利用reqresgraphQLParams参数。

app.use(
  '/graphql',
  graphqlHTTP((req, res, graphQLParams) => {
    return {
      schema,
      // other options
      context: {
        user: req.user,
        // whatever else you want
      }
    }
  })
)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM