Ger*_*áth 1 express apollo graphql apollo-server
在 apollo-server 3 中,我可以在创建 apollo 服务器时设置上下文,如下所示:
const server = new ApolloServer({
debug: true,
schema: executableSchema,
context: contextFunction(secretValues),
...
Run Code Online (Sandbox Code Playgroud)
我的contextFunction看起来像这样:
export const contextFunction =
(secretValues: AwsSecretValues) =>
async ({ req, res }: ExpressContext) => {
const sessionId = extractSessionIdFromCookies(req.headers.cookie);
const session = await validateSession(
sessionId || req.headers.authorization,
);
if (session) {
session.set({ expiresAt: Date.now() + DEFAULT_SESSION_EXTEND_TIME });
await session.save();
generateCookie(session._id, res);
}
return {
pubsub,
dataLoaders: dataLoaderFactory(),
session,
req,
res,
secretValues,
};
};
Run Code Online (Sandbox Code Playgroud)
它很有用,因为我不必在每个解析器上独立刷新会话,并且每个解析器都有它的最新版本,而且我还能够传递一堆其他有用的东西。
据我所知,apollo-server 4 中没有此选项。但是,如果您无法设置上下文(除了将内容深入到子解析器),那么上下文的全部意义是什么?一定有办法,但找不到办法。
如文档中所述,定义相同的新方法是:
app.use(
// A named context function is required if you are not
// using ApolloServer<BaseContext>
expressMiddleware(server, {
context: async ({ req, res }) => ({
token: await getTokenForRequest(req),
}),
}),
);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1726 次 |
| 最近记录: |