首页 > 解决方案 > 如何根据 NestJs 上的请求实现模式设计

问题描述

我有一个带有两个查询引擎的控制器:它定义了要使用的引擎(我现在有 6 个)和 q:这是搜索词。

    if (query.engine == 'nytimes') {
      return this.nytimesService.search(query.q);
    }
    if (query.engine == 'theguardian') {
      return this.theguardianService.search(query.q);
    }
    if (query.engine == 'catcher') {
      return this.newscatcherService.search(query.q);
    }
    if (query.engine == 'newsapi') {
      return this.newsapiService.search(query.q);
    }
    if (query.engine == 'newsdata') {
      return this.newsdataService.search(query.q);
    }
    if (!req.user?.id) {
      return 'To search on all engines should be authenticated';
    } else if (query.engine == 'any') {
      return this.summarizeService.search(query.q);
    }
    return 'Unknown engine'

在取决于引擎的控制器上,我调用相应的服务并调用搜索方法。在服务上,定义了向 api(theguardian, nytimes, ...) 发出请求的逻辑,并对其中的数据进行规范化。

@Injectable()
export class TheGuardianService {
  constructor(
    private readonly httpService: HttpService,
    private readonly configService: ConfigService,
  ) {}

  private buildUrl(termOfSearch: string) {
    const apiKey = this.configService.get<string>('THEGUARDIAN_API_KEY');
    const base = this.configService.get('THEGUARDIAN_API_URL');
    return base + `&api-key=${apiKey}` + `&q=${termOfSearch}`;
  }

  search(termOfSearch: string): Observable<{ data: Observable<News[]> }> {
    const url = this.buildUrl(termOfSearch);
    return this.httpService.get(url).pipe(
      map((res) => {
        const { response } = res.data;
        if (response.results.length == 0) {
          throw new NotFoundException('TheGuardian Service: News not found');
        }
        return {
          engine: 'The Guardian Api',
          total_news: response.pageSize,
          data: response.results.map(
            (element) =>
              new News(
                element.webUrl,
                element.webTitle,
                element.webPublicationDate,
              ),
          ),
        };
      }),
    );
  }
}

标签: typescriptdesign-patternsnestjsfactory

解决方案


推荐阅读