小编Kar*_*lam的帖子

如何将依赖注入与自定义装饰器集成

我正在尝试创建一个需要依赖注入的装饰器。例如:

@Injectable()
class UserService{
  @TimeoutAndCache(1000)
  async getUser(id:string):Promise<User>{
     // Make a call to db to get all Users
  }
}

Run Code Online (Sandbox Code Playgroud)

@TimeoutAndCache 返回一个新的承诺,它执行以下操作:

  1. 如果调用时间超过 1000 毫秒,则返回一个拒绝,当调用完成时,它会存储到 redis(以便下次可以获取)。
  2. 如果调用时间少于 1000 毫秒,只需返回结果
export const TimeoutAndCache = function timeoutCache(ts: number, namespace) {
  return function log(
    target: object,
    propertyKey: string,
    descriptor: TypedPropertyDescriptor<any>,
  ) {
    const originalMethod = descriptor.value; // save a reference to the original method
    descriptor.value = function(...args: any[]) {
      // pre
      let timedOut = false;
      // run and store result
      const result: Promise<object> = …
Run Code Online (Sandbox Code Playgroud)

dependency-injection nestjs

2
推荐指数
1
解决办法
2130
查看次数

如何让 EventPattern 在 Nest JS 中工作

我正在两个 NestJS 实例之间设置基本的 EventPattern。但是,其他微服务并未发出/接收该事件。

我试图在文档中找到一些具体的例子,但是看起来设置与调用 clinet.emit/client.call 来调用其他微服务不同。

微服务 1.

import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
import { Client, Transport, ClientProxy, ClientsModule, EventPattern } from '@nestjs/microservices';
import { Observable } from 'rxjs';


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

  @Client({ transport: Transport.REDIS })
  client: ClientProxy;

  @Get()
  async call(): Promise<number> {
    const pattern = { cmd: 'sum' };
    const payload = [1, 2, 3];
    const result = await this.client.emit('user_created', {age: 5});
    return …
Run Code Online (Sandbox Code Playgroud)

nestjs

2
推荐指数
1
解决办法
2868
查看次数

标签 统计

nestjs ×2

dependency-injection ×1