typescript - 如何根据 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,
),
),
};
}),
);
}
}
解决方案
推荐阅读
- python - Django 选择对象未将 id 传递给 URL
- java - 无法使用java客户端访问docker for windows中的rabbitmq
- android - 在 Audio Manager 对象上发送额外数据以确保 android.media.RINGER_MODE_CHANGED Action Receiver 接收到此信息
- postgresql - Postgres/jOOQ 替换 jsonb[] 元素
- excel - 堆叠数据并添加折线
- python - 如何用虚线连接散点图的点?
- symfony - Symfony 5 httpClient Windows AD 连接
- r - 将数据框中的列分成其他几列
- .net - 突然得到:HTTP 请求未经授权,客户端身份验证方案“协商”
- python - 从每个客户 id 的下一列中识别最后一个 yes 值和 0,然后从上一行下一列 pandas 中获取值