【发布时间】: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