Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Assign route dynamically Node/Express

I need dynamically assign a new route but it for some reason refuses to work.
When I send a request in the Postman it just keeps waiting for a response

The whole picture of what I am doing is the following:

I’ve got a controller with a decorator on one of its methods

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

@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)
                    })
                })
            }
        }
    }
}

Is it possible to dynamically set the route in the way?
I mainly use GraphQL but sometimes I need RESTful API too. So, I want to solve this by that decorator

>Solution :

In order for the response to finish, there must be a res.end() or res.json(...) or similar. But I cannot see that anywhere in your code.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading