【问题标题】:Assign route dynamically Node/Express动态分配路由 Node/Express
【发布时间】:2022-01-23 22:27:03
【问题描述】:

我需要动态分配一条新路线,但由于某种原因它拒绝工作。 当我在 Postman 中发送请求时,它只是一直在等待响应

我正在做的事情的全貌如下:

我有一个控制器,它的一个方法上有一个装饰器

@Controller()
export class Test {


    @RESTful({
        endpoint: '/product/test',
        method: 'post',
    })
    async testMe() {

        return {
            type: 'hi'
        }
        
    }


}
export function RESTful({ endpoint, method, version }: { endpoint: string, version?: string, method: HTTPMethodTypes }) {

    return function (target: any, propertyKey: string, descriptor: PropertyDescriptor): void {
        const originalMethod = descriptor.value

        Reflect.defineMetadata(propertyKey, {
            endpoint,
            method,
            propertyKey,
            version
        }, target)

        return originalMethod
    }
}

export function Controller() {

    return function (constructor: any) {
        const methods = Object.getOwnPropertyNames(constructor.prototype)
        Container.set(constructor)

        for (let action of methods) {

            const route: RESTfulRoute = Reflect.getMetadata(action, constructor.prototype)

            if (route) {

                const version: string = route.version ? `/${route.version}` : '/v1'

                Container.get(Express).injectRoute((instance: Application) => {
                    instance[route.method](`/api${version}${route.endpoint}`, async () => {
                        return await Reflect.getOwnPropertyDescriptor(constructor, route.propertyKey)
                        // return await constructor.prototype[route.propertyKey](req, res)
                    })
                })
            }
        }
    }
}

是否可以在途中动态设置路线? 我主要使用 GraphQL,但有时我也需要 RESTful API。所以,我想通过那个装饰器来解决这个问题

【问题讨论】:

  • @HeikoTheißen 当然!!!我知道这将是一个愚蠢的错误))把它放在答案中我会选择它)
  • 非常感谢您的光临!)@HeikoTheißen

标签: node.js typescript express metaprogramming


【解决方案1】:

为了完成响应,必须有 res.end()res.json(...) 或类似名称。但我在您的代码中的任何地方都看不到。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-04
    • 2022-01-07
    • 2016-07-23
    • 1970-01-01
    • 2018-04-23
    • 2018-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多