Nest JS - 关于将参数传递给装饰器

问题描述 投票:0回答:1

我正在研究缓存机制。 我需要一个动态缓存密钥。 (模块-方法名称-一些请求参数) 像这样: usersModule_getUserById_5

@CacheKey('userModule_getUserById' +request.body.id)

这个装饰器可以传递参数吗?

我将在用户数据更改时使用带有模块名称或方法名称或用户 ID 的清除缓存。

我已经准确指定了我想要下面的示例代码的位置。

import {
  CacheInterceptor,
  CacheKey,
  CacheTTL,
  Controller,
  Get,
  Req,
  UseInterceptors,
} from '@nestjs/common';
import { AppService } from './app.service';

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @UseInterceptors(CacheInterceptor)
  @CacheTTL(3600)
  @CacheKey('userModule_getUserById.....') // ----> I need a dynamic request parameters on this decorator.
  @Get()
  async getHello(@Req() req: Request): Promise<string> {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve('Hello World!');
      }, 3000);
    });
  }
}
typescript caching nestjs decorator interceptor
1个回答
0
投票

正如 Lior Kupers 在评论中建议的那样,您可以将

@CacheKey
装饰器包装在另一个装饰器中,并使用它来动态设置
Cache Key

下面是代码片段:

import { createParamDecorator, ExecutionContext } from "@nestjs/common";
import { Request } from "express";
import { CacheKey } from "@nestjs/cache-manager";

export type DynamicCacheKeyCallBack = (req: Request ) => string;

export const DynamicCacheKey = createParamDecorator<
  DynamicCacheKeyCallBack,
  ExecutionContext
>((cb: DynamicCacheKeyCallBack, ctx: ExecutionContext) => {
  const request: Request = ctx.switchToHttp().getRequest();

  const key = cb(request) ?? "";
  return CacheKey(key);
});

// in a controller.ts, use the decorator as below
@DynamicCacheKey(req => req.isAuthenticated.toString() )
@Get()
getProducts() {
  return []
}
© www.soinside.com 2019 - 2024. All rights reserved.