使用普通GraphQl Server,我们可以定义上下文对象:
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'
});
您可以在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
函数的args中获得了来自请求的所有数据。