import LRUCache from 'lru-cache' ; import { Storage , StorageOptions } from './Storage' ; import { getStorageFactory , FactoryStorageOption } from './Factory' ; const DEFAULT_MAX_SIZE = 1000 ; const defaultSizeCalculator = ( ) => 1 ; export type ManagerStorageOption < O extends StorageOptions = any > = FactoryStorageOption < O > & { id : string ; } ; export type StorageManagerOptions = { maxSize ? : number ; sizeCalculator ? : ( value : Storage , key : string ) => number ; } ; const DEFAULT_MANAGER = { maxSize : DEFAULT_MAX_SIZE , sizeCalculator : defaultSizeCalculator } ; export class StorageManager { /** Cache map */ private storages : LRUCache < string , Storage > ; constructor ( options = DEFAULT_MANAGER ) { const { maxSize , sizeCalculator } = options ; this . storages = new LRUCache ( { max : maxSize , length : sizeCalculator } ) ; } param id has ( id ) { return this . storages . has ( id ) ; } param id get < O extends StorageOptions = any > ( id ) { const storage = this . storages . get ( id ) ; if ( ! storage ) throw new Error ( 'Storage not found.' ) ; return storage ; } remarks param options param ttl async getOrCreate < O extends StorageOptions > ( options , ttl ? ) { if ( ! options . id ) return this . create ( options , ttl ) ; try { return this . get ( options . id ) ; } catch ( ex ) { return this . create ( options , ttl ) ; } } remarks param options param ttl async create < O extends StorageOptions > ( options , ttl ? ) { const storage = getStorageFactory ( ) . create ( options ) ; this . storages . set ( options . id , storage , ttl ) ; return storage ; } } const storageManager = new StorageManager ( ) ; export function getStorageManager ( ) { return storageManager ; }