mgechev / aspect.js

JavaScript library for aspect-oriented programming using modern syntax.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Method parameters

fab1o opened this issue · comments

commented

Is there a way to include a list of the method's param names in the metadata?

export class MethodMetadata {
+ public params: string[];
  public proceed: boolean;
  public name: string;
  public args: any[];
  public context: any;
  public result: any;
  public exception: any;
  public invoke: (...args: any[]) => any;
}

My concern will be that if the code goes through a minifier the names could be mangled. Could you instead rely on the position of the arguments?

commented

I'm not sure this is the best tool for what I'm trying to accomplish. Maybe you can help me figure this out.

My idea is to create a decorator where it would validate the function arguments. The decorator would check every argument in args against a user defined list of types.

The idea is that the decorator would receive a list of parameter names too so that when a bad type check occurs, we can present the message to the user like this:

Called ${meta.className}.${meta.method.name} ${meta.params[0]} expected ${meta.types[0]} but received ${meta.method.args[0]}

Although, I'd certainly go with TypeScript because of its static checks, you can still accomplish this with aspect.js.

You can specify the types and rely on the position of the arguments. You can have something like:

import { string, number, optional, object } from 'my-types';

class Foo {
  @types(string, number, [optional, object])
  bar(a, b, c) {
    // body
  }
}

class TypeCheckingAspect {
  @beforeMethod({
    classes: [Foo],
    methods: [Foo.prototype.bar]
  })
  invokeBeforeMethod(meta: Metadata) {
    // type check
  }
}
commented

I can't use TypeScript for this, the idea is to type check on run-time.

Although I can use the tool today, I won't be able to write a good informative message to the user if I don't know the name of the parameter. A suitable message is this:

"Foo.bar(a, b, c) a expected string but received null"

Shouldn't be hard to write a message. As a parameter of the aspect you get reference to the method. If you invoke args.method.toString() you can extract the signature and look up the parameter name.