hugoviktor
4/17/2020 - 7:16 PM

Custom NestJS http cache interceptor for POST Method

Custom Http Interceptor for support cache in POST Method for NestJS Framework.

import {CacheInterceptor, ExecutionContext, Injectable} from '@nestjs/common';
import {CACHE_KEY_METADATA} from "@nestjs/common/cache/cache.constants";
import {Md5} from 'ts-md5/dist/md5';

@Injectable()
export class HttpCacheInterceptor extends CacheInterceptor {


    trackBy(context: ExecutionContext): string | undefined {
        const httpAdapter = this.httpAdapterHost.httpAdapter;
        const isHttpApp = httpAdapter && !!httpAdapter.getRequestMethod;
        const cacheMetadata = this.reflector.get(
            CACHE_KEY_METADATA,
            context.getHandler(),
        );

        if (!isHttpApp || cacheMetadata) {
            return cacheMetadata;
        }

        const request = context.getArgByIndex(0);
        if (httpAdapter.getRequestMethod(request) == 'GET') {
            return httpAdapter.getRequestUrl(request);
        }


        const body = request.body
        body.q = request.query["q"];
        const strBody = JSON.stringify(body);
        const key = Md5.hashStr(strBody);
        console.log(key)
        return key.toString();
    }


}