1
1
import axios , { AxiosResponse , isAxiosError } from 'axios'
2
2
import { Axios } from 'axios'
3
- import { NextFunction , Request , Response } from 'express'
3
+ import { Request , Response } from 'express'
4
4
5
5
const COINGECKO_API_KEY = process . env . COINGECKO_API_KEY
6
6
@@ -10,24 +10,22 @@ const CACHE_TTL_MS = 60_000
10
10
11
11
type RequestCache = Partial < Record < string , AxiosResponse > >
12
12
13
- export class Markets {
13
+ export class CoinGecko {
14
14
private axiosInstance : Axios
15
15
private requestCache : RequestCache
16
16
17
17
constructor ( ) {
18
18
this . requestCache = { }
19
19
this . axiosInstance = axios . create ( {
20
- baseURL : 'https://pro-api.coingecko.com/' ,
20
+ baseURL : 'https://pro-api.coingecko.com/api/v3/ ' ,
21
21
headers : {
22
22
'x-cg-pro-api-key' : COINGECKO_API_KEY ,
23
23
} ,
24
24
} )
25
25
}
26
26
27
- async handler ( req : Request , res : Response , next : NextFunction ) : Promise < void > {
28
- const url = req . url . substring ( '/markets/' . length )
29
-
30
- if ( ! url . startsWith ( 'api/v3/' ) ) return next ( )
27
+ async handler ( req : Request , res : Response ) : Promise < void > {
28
+ const url = req . url . substring ( '/api/v1/markets/' . length )
31
29
32
30
const cachedResponse = this . requestCache [ req . url ]
33
31
if ( cachedResponse ) {
@@ -40,7 +38,7 @@ export class Markets {
40
38
41
39
try {
42
40
const response = await this . axiosInstance . get ( url )
43
- this . requestCache [ url ] = response
41
+ this . requestCache [ req . url ] = response
44
42
Object . entries ( response . headers ) . forEach ( ( [ k , v ] ) => res . set ( k , v ) )
45
43
res . status ( response . status ) . send ( response . data )
46
44
} catch ( err ) {
@@ -52,7 +50,7 @@ export class Markets {
52
50
res . status ( 500 ) . send ( 'Internal Server Error' )
53
51
}
54
52
} finally {
55
- setInterval ( ( ) => delete this . requestCache [ url ] , CACHE_TTL_MS )
53
+ setInterval ( ( ) => delete this . requestCache [ req . url ] , CACHE_TTL_MS )
56
54
}
57
55
}
58
56
}
0 commit comments