GraphQL ContextGraphQL 上下文
You can use your configuration to populate the GraphQL context based on the wider context in which the GraphQL request is being executed.
你可以通过配置,根据 GraphQL 请求所处的整体运行环境来填充 GraphQL 上下文(context)。
Making HTTP data available to plan resolvers让 plan resolver 访问 HTTP 请求数据
Using the grafast.context callback we can extract data from the incoming HTTP
request and make it accessible from within the Grafast schema via the GraphQL context.
通过 grafast.context 回调函数,我们可以从传入的 HTTP 请求中提取数据,并借助 GraphQL 上下文让 Grafast schema 内部能够访问这些数据。
Example:
示例:
export default {
grafast: {
async context(requestContext, args) {
const req = requestContext.node?.req;
// You can perform asynchronous actions here if you need to; for example
// looking up the current user in the database.
// Return here things that your resolvers need
return {
// Return the current user from Passport.js or similar
user: req.user,
// Add a helper to get a header
getHeader(name) {
return req?.get(name);
},
// Give access to the database-owner PostgreSQL pool, for example to
// perform privileged actions
rootPgPool,
};
},
},
};
When adding details to grafast.context, you must careful to not add properties that
will clash with system context keys such as withPgClient, pgSettings,
pgSubscriber and jwtClaims (you can see the existing context keys by
inspecting the contextValue property of second argument to the grafast.context
callback: args.contextValue).
向 grafast.context 添加自定义字段时,务必避免与系统内置的上下文键名发生冲突,例如 withPgClient、pgSettings、pgSubscriber 和 jwtClaims(你可以通过查看 grafast.context 回调第二个参数的 contextValue 属性,即 args.contextValue,来了解当前已有的上下文键名)。
For the absolute best future compatibility, we recommend that you prefix your context keys with your initials, company name, or similar.
为了确保最佳的向后兼容性与未来扩展性,建议为自定义上下文键名加上你的名字缩写、公司名称或类似前缀。
It’s not a good idea to give direct access to the req or res objects
via grafast.context as it binds the GraphQL context too tightly to the HTTP
request lifecycle — this will cause you issues if you try and use the GraphQL
schema in other contexts (e.g. directly from the application, in integration
tests, or over alternative transports such as websockets for realtime).
Instead, add helpers to get/set the data you need that can be implemented in
each future situation.
不要通过 grafast.context 直接暴露 req 或 res 对象,这会让 GraphQL 上下文与 HTTP 请求生命周期耦合过紧——一旦你需要在其他场景中使用该 GraphQL schema(例如在应用内部直接调用、在集成测试中运行,或通过 WebSocket 等其他传输方式提供实时能力),就会遇到问题。相反,应当在上下文中提供用于读取或设置所需数据的辅助函数,以便在各种运行环境下灵活实现。