mgechev / aspect.js

JavaScript library for aspect-oriented programming using modern syntax.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

`Wove` automatically when `classes` is being used

SamVerschueren opened this issue · comments

Would it be possible to automatically wove a target when it is being used in a classes array?

class Article {
  id: number;
  title: string;
  content: string;
}

class ArticleCollection {
  articles: Article[] = [];
  getArticle(id: number) {
    console.log(`Getting article with id: ${id}.`);
    return this.articles.filter(a => {
      return a.id === id;
    }).pop();
  }
  setArticle(article: Article) {
    console.log(`Setting article with id: ${article.id}.`);
    this.articles.push(article);
  }
}
import { ArticleCollection } from './article-collection';

class LoggerAspect {
  @beforeMethod({
    classes: [ArticleCollection],
    methodNamePattern: /^(get|set)/
  })
  invokeBeforeMethod(meta: Metadata) {
    console.log(`Inside of the logger. Called ${meta.className}.${meta.method.name} with args: ${meta.method.args.join(', ')}.`);
  }
}

I'm back and forth on this one (if it would be possible but I don't see a reason why it wouldn't be possible).

The reason I would like this is that in this case the ArticleCollection is not aware at all of something being attached to it. No extra work for the developer to let it work.

The reason I wouldn't like it is because when looking at the code, you can't detect that a method could run side effects. Although, if we would go for it, nothing keeps the developer from adding @Wove() to the class just to make it clear for every other developer working on the project.

Happy to do a PR but wanted to discuss this first.

@SamVerschueren good suggestion. It's possible and looks to me like a good idea. I can add it in my backlog for later this month.

If you'd have time for PR, I'll be happy to help with the review and merge it.

Can you please update npm package due to this feature?