import { asGlobalInterceptor , inject , injectable , Interceptor , InvocationContext , InvocationResult , Provider , ValueOrPromise , } from '@loopback/core' ; import { RestBindings } from '@loopback/rest' ; import debugFactory from 'debug' ; import { CachingService } from '../caching-service' ; import { CACHING_SERVICE } from '../keys' ; const debug = debugFactory ( 'greeter-extension' ) ; @ injectable ( asGlobalInterceptor ( 'caching' ) ) export class CachingInterceptor implements Provider < Interceptor > { constructor ( @ inject ( CACHING_SERVICE ) private cachingService ) { } value ( ) { return async ( ctx , next ) => { const httpReq = await ctx . get ( RestBindings . Http . REQUEST , { optional : true , } ) ; if ( ! httpReq ) { return next ( ) ; } const key = httpReq . path ; const lang = httpReq . acceptsLanguages ( [ 'en' , 'zh' ] ) || 'en' ; const cachingKey = `${ lang }:${ key }` ; const cachedResult = await this . cachingService . get ( cachingKey ) ; if ( cachedResult ) { debug ( 'Cache found for %s %j' , cachingKey , cachedResult ) ; return cachedResult ; } const result = await next ( ) ; await this . cachingService . set ( cachingKey , result ) ; return result ; } ; } }