lundi 15 novembre 2021

How implement a pattern design on a request on NestJs

I have a controller with with two queries engine: which defines the engine to use(i have 6 at the moment) and q: which is the term of search.

    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'

On the controller depending on engine I call to the corresponding service and call the search method. On the service a logic to make the request to the api(theguardian, nytimes, ...) is defined and normalize the data inside of it.

@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,
              ),
          ),
        };
      }),
    );
  }
}

Aucun commentaire:

Enregistrer un commentaire