我想知道如何在type-graphql中使用RESTDataSource,从而在redis中正确地缓存。如果能举个小例子,我会很感激的。
目前,我使用DI容器来获取服务,该服务是从RestDataSource类扩展而来的,但这不是正确的方式。
BookmarkResolver.ts
import { Resolver, FieldResolver, Root, Query, Ctx, Authorized } from 'type-graphql';
import { DealService } from '../service/DealService';
import { AvailableLocale } from '../enum/AvailableLocale';
import { Bookmark } from '../entity/Bookmark';
@Resolver(_of => Bookmark)
export class BookmarkResolver {
constructor(private dealService: DealService) {}
@FieldResolver()
async wordpressDeal(@Root() bookmark: Bookmark) {
return await this.dealService.getDealById(bookmark.item_id, AvailableLocale.STAGING);
}
}DealService.ts
import { Service } from 'typedi';
import { AbstractService } from './AbstractService';
import { AvailableLocale } from '../enum/AvailableLocale';
@Service()
export class DealService extends AbstractService {
baseURL = process.env.DEAL_SERVICE_URL;
async getDealById(dealId: string | number, locale: AvailableLocale) {
const response = await this.get(
'deals/' + dealId,
{ locale }
);
return this.dealReducer(response);
}
dealReducer(deal: any) {
return {
id: deal.id || 0,
title: deal.title
};
}
}AbstractService.ts
import { RESTDataSource, HTTPCache } from 'apollo-datasource-rest';
import { Service } from 'typedi';
@Service()
export class AbstractService extends RESTDataSource {
constructor() {
super();
this.httpCache = new HTTPCache();
}
}发布于 2021-05-14 22:48:11
通过ApolloServer的上下文共享RESTDataSource。通过@Ctx()装饰器访问上下文,在解析器中使用它。
1.定义RESTDataSource
根据apollo-datasource-rest example定义数据源。
export class TodoDataSource extends RESTDataSource {
constructor() {
super();
this.baseURL = "https://jsonplaceholder.typicode.com/todos";
}
async getTodos(): Promise<Todo[]> {
return this.get("/");
}
}2.创建DataSource实例并将其放入上下文中
当您启动服务器时,通过定义一个创建数据源的函数来add data sources to the context。
const server = new ApolloServer({
schema,
playground: true,
dataSources: () => ({
todoDataSource: new TodoDataSource(),
}),
});3.访问解析器中的DataSource
使用@Ctx()装饰器访问解析器中的上下文,以便可以使用数据源。
@Resolver(Todo)
export class TodoResolver {
@Query(() => [Todo])
async todos(@Ctx() context: Context) {
return context.dataSources.todoDataSource.getTodos();
}
}https://github.com/lauriharpf/type-graphql-restdatasource上完整的、可运行的示例
https://stackoverflow.com/questions/59682119
复制相似问题