import { Action } from '../client/client.types' ; import { Cache } from './cache.types' ; export const convertActionToBase64 = ( action ) => { return Buffer . from ( JSON . stringify ( action ) ) . toString ( 'base64' ) ; } ; export const createCache = < T > ( isCacheable , isValid ) => { let items = { } ; const add = ( action , value ) => { if ( isCacheable ( action ) ) { items [ convertActionToBase64 ( action ) ] = { ... value , timestamp : Date . now ( ) } ; } } ; const remove = ( action ) => { delete items [ convertActionToBase64 ( action ) ] ; } ; const get = ( action ) => { const response = items [ convertActionToBase64 ( action ) ] ; const valid = response && isValid ( response ) ; if ( valid ) { return response ; } if ( response && ! valid ) { remove ( action ) ; } } ; const setItems = ( value ) => { items = value ; } ; const getItems = ( ) => { return items ; } ; return { add , get , getItems , remove , setItems , } as Cache < T > ; } ;