@@ -4,6 +4,11 @@ import { HttpError } from "../errors/HttpError";
44import { getCacheStore } from "../cache/store" ;
55import { UPSTREAM_TIMEOUT_MS } from "../config/upstream" ;
66import { ArticleSearchFilters , ArticleSearchOptions } from "../types/search" ;
7+ import {
8+ cacheEventsTotal ,
9+ upstreamRequestDurationSeconds ,
10+ upstreamRequestsTotal ,
11+ } from "../metrics/register" ;
712
813const API_KEY = process . env . GNEWS_API_KEY ;
914const BASE_URL = "https://gnews.io/api/v4" ;
@@ -50,25 +55,36 @@ export const fetchArticles = async (options: ArticleSearchOptions): Promise<Arti
5055 const store = getCacheStore ( ) ;
5156 const cached = await store . get ( cacheKey ) ;
5257 if ( cached ) {
58+ cacheEventsTotal . inc ( { result : "hit" } ) ;
5359 return cached as Article [ ] ;
5460 }
61+ cacheEventsTotal . inc ( { result : "miss" } ) ;
5562
63+ const stopUpstreamTimer = upstreamRequestDurationSeconds . startTimer ( ) ;
64+ let articles : Article [ ] ;
5665 try {
5766 const response = await axios . get < { articles : Article [ ] } > ( `${ BASE_URL } /search` , {
5867 params : toProviderParams ( options ) ,
5968 timeout : UPSTREAM_TIMEOUT_MS ,
6069 validateStatus : ( s ) => s >= 200 && s < 300 ,
6170 } ) ;
6271
63- const articles = normalizeArticles ( response . data ) ;
64- await store . set ( cacheKey , articles ) ;
65- return articles ;
72+ articles = normalizeArticles ( response . data ) ;
73+ upstreamRequestsTotal . inc ( { outcome : "success" } ) ;
74+ stopUpstreamTimer ( { outcome : "success" } ) ;
6675 } catch ( err ) {
76+ const outcome =
77+ err instanceof HttpError && err . statusCode === 502 ? "invalid_payload" : "error" ;
78+ upstreamRequestsTotal . inc ( { outcome } ) ;
79+ stopUpstreamTimer ( { outcome } ) ;
6780 if ( axios . isAxiosError ( err ) ) {
6881 throw new HttpError ( 502 , "Upstream news service unavailable" ) ;
6982 }
7083 throw err ;
7184 }
85+
86+ await store . set ( cacheKey , articles ) ;
87+ return articles ;
7288} ;
7389
7490export const fetchArticlesByTitle = async ( title : string ) : Promise < Article | undefined > => {
0 commit comments