【问题标题】:How to define context object for graphql subscription server如何为 graphql 订阅服务器定义上下文对象
【发布时间】:2018-02-20 17:04:37
【问题描述】:

使用普通的 graphql 服务器,我们可以像这样定义上下文对象:

app.use('/graphql', graphqlExpress(async (req) => {
    return {
      schema,
      context: {
        app,
        params,
      }
    };
  }));

**订阅服务器**

如何为订阅服务器做同样的事情? (做混合http / websocket方法)。似乎无法从文档中找到解决方案。

new SubscriptionServer({
    execute,
    subscribe,
    schema,
    onConnect: (connectionParams, webSocket) => {
      console.log(connectionParams);
    }
  }, {
    server,
    path: '/subscriptions'
  });

【问题讨论】:

    标签: graphql graphql-subscriptions


    【解决方案1】:

    您可以在execute 函数之前添加一个中间件,并在解析订阅之前添加所需的上下文。

    它可能看起来像这样:

    const middleware = (args) => new Promise((resolve, reject) => {
          const [schema, document, root, context, variables, operation] = args;
          
          context.app = <your app parameter>;
          context.params = <your params>;
          
          resolve(args);
    });
    
    
    SubscriptionServer.create({
      schema,
      subscribe,
      execute: (...args) => middleware(args).then(args => { return execute(...args); }) },
      {
        server: httpServer,
        path: "/subscription",
      },
    );

    如您所见,execute 函数的参数中包含来自请求的所有数据。

    【讨论】:

      猜你喜欢
      • 2017-12-05
      • 2020-08-25
      • 2019-04-14
      • 2022-11-08
      • 2020-12-03
      • 2020-03-24
      • 1970-01-01
      • 2017-07-27
      • 1970-01-01
      相关资源
      最近更新 更多