我正在尝试设置一个分阶段构建请求上下文的 Apollo Express 服务器: 首先,通过处理输入和确定预期上下文状态的插件;其次,上下文函数处理当前上下文状态并最终确定上下文状态(通过添加额外数据)。
Tl;dr 我在设置强大的 Apollo 插件定义和上下文函数时遇到了问题,但我觉得我对这些进程的运行时顺序做出了错误的假设。
return new ApolloServer({
schema,
introspection: true,
plugins: [
AggregatorPipePlugin(),
...
],
context: createLegacyServerContext,
});
设置Apollo Server,其插件运行以拦截操作类型和授权。
它的上下文函数有望在插件完成后处理请求的执行。
export const createLegacyServerContext: ApolloServerExpressConfig['context'] =
async (context): Promise<ApolloContext> => {
const {req} = context;
const {body} = req;
if (!body.operationName) {
return {role: 'user'};
}
const {identifier, role} = body;
if (identifier && role) {
...
return {
role, identifier, ...rest
}
} else {
throw new AuthenticationError(
'Unable to identify incoming request identity.',
);
}
};
上下文函数,如果请求用户被识别,我们添加额外的数据以帮助解析器中的处理。
const AggregatorPipePlugin = {
async requestDidStart(requestContext: GraphQLRequestContext) {
const {context, request} = requestContext;
const authorization = request.http?.headers.get('Authorization');
if (authorization) {
const idToken = authorization.replace('Bearer ', '');
try {
...
Object.assign(requestContext.context, obj);
...
} else {
throw new Error('Missing or invalid claims.');
}
} catch (error) {
throw new Error(
`Authentication Provider failed verification. ${error}`,
);
}
} else {
throw new Error('Missing or invalid authorization.');
}
},
};
插件抽象地具有以下职责: