NodeJS js:将从请求返回参数的自定义装饰器

a0zr77ik  于 2023-10-17  发布在  Node.js
关注(0)|答案(1)|浏览(98)

在一个自定义装饰器Param中,我有一个console.log,它只运行一次。如何让它像在nestjs中一样在每次请求时返回一个新的id值?

@Get('/:id')
async findUser (
    @Param() id: string | undefined // is not called each time when acces method findUser
  ): Promise<User> {
}


export const Param = () => (target: any, key: string, index: number)  => {
    var indices = Reflect.getMetadata('request', target, key);
    console.log('test', indices)
}


Reflect.defineMetadata('request', event, currentController.prototype, route.methodName);
wvt8vs2t

wvt8vs2t1#

decorator.ts

export const Param = (name) => (target: any, propertyKey: string, index: number)  => {
    // Set parameter name.
    Reflect.defineMetadata('param', name, target, propertyKey);
}

export const Get = (url) => (target: any, propertyKey: string)  => {
    // Set method and url.
    Reflect.defineMetadata('route', { method: 'get', url }, target, propertyKey);
}

controller.ts

import { Get, Param } from 'decorator.ts';

class Controller {
    @Get('/:id')
    async findUser (
        @Param('id') id: string | undefined 
      ): Promise<User> {
    }
}

server.ts

import { Controller } './controller.ts'

const router = require('express').Router();

for (let propertyKey of Object.getOwnPropertyNames(Controller.prototype)) {
   // Read metadata created by decorators.
   var param = Reflect.getMetadata('param', target, propertyKey);
   var route = Reflect.getMetadata('method', target, propertyKey);

   // Add routes using data from decorators.
   router[route.method]('route.url', (req, res) => {
   // Call needed method of controller.
       return Controller[propertyKey](req.params[param]);
   });
}

相关问题