import { NowRequest , NowResponse } from '@vercel/node' ; import got from 'got' ; import config from '../src/config' ; import { MtaPathKeys } from './_constants' ; const { mta } = config ; const cache = { } ; const get = async ( url , params ) => { const parsedUrl = url . replace ( /:([^\/]+)/g , ( _ , key ) => params [ key ] || '' ) ; return got ( parsedUrl , { responseType : 'json' } ) ; } ; export const passthrough = ( pathKey , cacheExpire ) => ( req , res ) : void => { const { query , url } = req ; if ( ! url ) { return ; } const urlString = url . toString ( ) ; if ( cacheExpire && cache [ urlString ] && cache [ urlString ] . expire >= Date . now ( ) ) { res . send ( cache [ urlString ] . data ) ; return ; } const params = { } ; for ( const [ key , value ] of Object . entries ( query ) ) { if ( typeof value === 'string' ) { params [ key ] = value ; } } get ( `${ mta . baseUrl }${ mta [ pathKey ] }` , params ) . then ( ( response ) => { const data = response . body ; if ( data && cacheExpire ) { cache [ urlString ] = { data , expire : Date . now ( ) + cacheExpire , } ; } res . json ( data ) ; } ) . catch ( ( e ) => { res . status ( 500 ) ; res . json ( { error : e . toString ( ) } ) ; } ) ; } ;