Can I get the names of variables in the decorator method?

653 views Asked by At

I want to write a decorator that could check the length of the parameters in the query, I have this method:

@httpPost("doAuth")
@ValidateSize([{login: {min: 6}}, {password: {min: 6}}])
public async auth(@requestBody("login") login :string, @requestBody("password") pass :string, @response() response :express.Response){
    let user :UserData = await this.authService.auth(login, pass);
    if(!user) return response.sendStatus(403);
    return user;
}

The decorator himself:

export function ValidateSize(param :Object) {
    return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
        return {
            value: function (...args: any[]) {
                //Here I need to get the variables login, pass that to check their length

            }
        };
    }
}

The problem is that args is an array with numeric indices, but I need to get arguments by their names. How can I do that?

1

There are 1 answers

0
lilezek On BEST ANSWER

As far as I know, TypeScript compiler does not emit metadata with variable names. There are projects trying to improve what the TypeScript compiler emits so decorators can be used to get more information about the code, like:

https://www.npmjs.com/package/awesome-metadata

But this project does not emit yet additional information about functions.

Disclaimer: I'm the author of this project.