import LRU from "lru-cache" ; import { reuseInFlight } from "async-await-utils/hof" ; import getPool from "./pool" ; import { Pool } from "pg" ; const MAX_AGE_S = { short : 5 , medium : 15 , long : 30 , minutes : 10 * 60 , infinite : 60 * 60 * 24 * 365 , } ; export type Length = keyof typeof MAX_AGE_S ; const caches = new Map ( ) ; for ( const length in MAX_AGE_S ) { caches [ length ] = new LRU < string , any > ( { max : 1000 , maxAge : 1000 * MAX_AGE_S [ length ] , } ) ; } const cachedQuery = reuseInFlight ( async ( length , ... args ) => { const cache = caches [ length ] ; if ( cache == null ) { throw Error ( `invalid cache "${ length }"` ) ; } const key = JSON . stringify ( args ) ; if ( cache . has ( key ) ) { return cache . get ( key ) ; } const pool = getPool ( ) ; const result = await pool . query ( ... args ) ; if ( result . rows . length > 0 ) { cache . set ( key , result ) ; } return result ; } ) ; export default function getCachedPool ( length ) { return { query : async ( ... args ) => await cachedQuery ( length , ... args ) , } as any as Pool ; }