【问题标题】:How can I use type-graphql and RESTDataSource如何使用 type-graphql 和 RESTDataSource
【发布时间】:2020-04-28 03:06:55
【问题描述】:

我想知道如何在 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();
  }
}

【问题讨论】:

    标签: typegraphql


    【解决方案1】:

    通过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 的实例并将其放入 Context

    当您启动服务器时,add data sources to the context 通过定义一个创建数据源的函数。

    const server = new ApolloServer({
      schema,
      playground: true,
      dataSources: () => ({
        todoDataSource: new TodoDataSource(),
      }),
    });
    

    3。访问解析器中的数据源

    使用 @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 上的完整、可运行示例

    【讨论】:

      猜你喜欢
      • 2021-03-09
      • 1970-01-01
      • 2017-07-10
      • 2020-07-24
      • 2021-01-09
      • 2021-01-03
      • 2020-06-27
      • 2019-09-23
      • 2019-08-07
      相关资源
      最近更新 更多