使用普通的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'
});
答案 0 :(得分:0)
您可以在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
函数的参数中拥有了请求中的所有数据。