duk*_*uke 5 javascript typescript apollo graphql apollo-server
遵循有关 dataSources的Apollo Server 文档,人们会假设在 GraphQL 解析器中访问数据的最佳方式是通过dataSources服务器配置上的选项。
但是,我正在开发的应用程序的要求会导致许多不同的数据源类(...在下面的handler.ts文件中被截断,但现在大约有 10 个,将来还会有更多)。这意味着每个数据源类都将针对服务器收到的每个查询/变异进行实例化,我认为如果我有足够的数据源类,这最终可能会导致一些延迟。
我正在考虑不使用该dataSources选项,而是根据需要通过使用解析器上下文来调用initialize()ApolloRESTDataSource类上的方法(下面粘贴的示例解析器方法)来实例化每个数据源类,这似乎为dataSources配置选项所做的数据源类。
我很好奇:
dataSources我不知道的选项有什么好处/坏处吗?提前感谢您的任何见解!
handler.ts 中的服务器配置:
const server = new ApolloServer({
typeDefs,
resolvers,
introspection: true,
playground: true,
dataSources: (): IDataSources => {
return {
entity: new Entity(),
notes: new Notes(), // this could be removed if "new" resolver method is used
... // like 8 more data sources go here
};
},
context: ({
event,
context
}: {
event: APIGatewayEvent;
context: Context;
}): IGraphqlServerOptionContext => {
const user = new User(event);
return { apiGatewayEvent: event, apiGatewayContext: context, user };
},
extensions: [() => new LogFunctionExtension()]
});
Run Code Online (Sandbox Code Playgroud)
来自resolvers.ts 的示例(替代)解析器方法:
export const resolvers: IResolvers<any, IResolverContext> = {
Query: {
getNotes: async (
_source,
args: QueryGetNotesArgs,
resolverContext: IResolverContext
) => {
validateRequestHeaders('common', resolverContext.apiGatewayEvent);
// old method of accessing notes data source class:
// const {
// dataSources: { notes }
// } = resolverContext;
// new method of accessing notes data source class:
const notes = new Notes(resolverContext);
return notes.getNoteDetails(args);
},
}
};
Run Code Online (Sandbox Code Playgroud)
新的 Notes 数据源类构造函数:
export default class Notes extends RESTDataSource<IDataSourceContext> {
constructor(inputContext: IDataSourceContext) {
this.initialize({
context: inputContext,
cache: new InMemoryLRUCache()
});
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1088 次 |
| 最近记录: |