1- const conf = require ( "./config" ) ;
2- const logger = ( require ( "log4js" ) ) . getLogger ( "Cache" ) ;
1+ import { expiration } from "./config" ;
2+ import { getLogger } from "log4js" ;
3+ const logger = getLogger ( "Cache" ) ;
34
45logger . level = "debug" ;
56
67
78class Cache {
8- protected caches : object ;
9+ protected caches : Record < string , Record < string , any > > ;
910 public expiration : number ;
10- constructor ( expiration : number ) {
11+ constructor ( ) {
1112 this . caches = { } ;
1213 this . expiration = expiration ;
1314 this . uptime ( ) ;
1415 }
1516
16- get ( key : string ) : undefined | any { /** @ts -ignore **/
17+ get ( key : string ) : undefined | any {
1718 const value = this . caches [ key ] ;
18- if ( this . exist ( key ) ) { // @ts -ignore
19+ if ( this . exist ( key ) ) {
1920 return JSON . parse ( value . value ) ;
2021 }
2122 }
2223
23- set ( key : string , value : any ) : void { // @ts -ignore
24+ set ( key : string , value : any ) : void {
2425 this . caches [ key ] = {
2526 value : JSON . stringify ( value ) ,
2627 expiration : ( new Date ( ) . getTime ( ) / 1000 ) + this . expiration ,
2728 }
2829 }
2930
30- exist ( key : string ) : boolean { // @ts -ignore
31+ exist ( key : string ) : boolean {
3132 const value = this . caches [ key ] ;
3233 return ( ! ! value ) && ( value . expiration > ( new Date ( ) . getTime ( ) / 1000 ) ) ;
3334 }
3435
35- remove ( key : string ) : boolean { // @ts -ignore
36+ remove ( key : string ) : boolean {
3637 return delete this . caches [ key ] ;
3738 }
3839
3940 uptime ( ) : void {
4041 const _this = this ;
4142 setInterval ( function ( ) {
4243 let n : number = 0 ;
43- for ( const key in _this . caches ) { // @ts -ignore
44+ for ( const key in _this . caches ) {
4445 if ( _this . caches [ key ] . expiration < ( new Date ( ) . getTime ( ) / 1000 ) ) {
4546 _this . remove ( key ) ; n ++ ;
4647 }
@@ -49,19 +50,17 @@ class Cache {
4950 } , this . expiration / 2 ) ;
5051 }
5152
52- wrap ( func : ( ...params : any [ ] ) => Promise < any > ) : ( ...params : any [ ] ) => Promise < any > {
53+ cache ( name : string , func : ( ...params : any [ ] ) => Promise < any > ) : ( ...params : any [ ] ) => Promise < any > {
5354 /**
5455 * Async Function Cache.
5556 */
5657
5758 const _this : Cache = this ;
58- const name : string = func . name [ 0 ] === "_" ? func . name . slice ( 1 ) : func . name ;
5959 return async function ( ...params : any [ ] ) {
6060 const key : string = name + params . toString ( ) ;
6161 if ( _this . exist ( key ) ) {
6262 return _this . get ( key ) ;
6363 } else {
64- /** @ts -ignore **/
6564 const response : any = await func ( ...params ) ;
6665 _this . set ( key , response ) ;
6766 return response ;
@@ -70,4 +69,4 @@ class Cache {
7069 }
7170}
7271
73- export const cache = new Cache ( conf . expiration ) ;
72+ export const cache = new Cache ( ) ;
0 commit comments