question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to use with other decorators?

See original GitHub issue
function logNew() {
  return <T extends constructor<any>>(constructor: T) => {
    return class extends constructor {
      constructor(...args: any[]) {
        super(...args);
        console.log("CREATED", args)
      }
    }
  };
}

class Foo {
  value = "foo"
}

@logNew()
@injectable()
class Bar {
  constructor(foo: Foo){
    console.log(foo.value)
  }
}

const bar = container.resolve(Bar)

foo is undefined

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:8 (1 by maintainers)

github_iconTop GitHub Comments

3reactions
cypherix93commented, Dec 5, 2020

I actually ran into this same issue and found out that I could just pass on the reflection metadata onto the new constructor. Now the new constructor gets called with the injected dependencies. Not sure if this is the correct approach, but it seems to work for now. See below:

const INJECTION_TOKEN_METADATA_KEY = 'injectionTokens';

export function MyDecorator(): ClassDecorator {
    return ((target: { new(...args: any[]): any }) => {
        const original = target;

        const injectionTokensMetadata = Reflect.getOwnMetadata(INJECTION_TOKEN_METADATA_KEY, original) || {};

        const wrapper = function (...args: any[]) {
                // args here have the injected constructor dependencies
        };

        wrapper.prototype = original.prototype;

        Reflect.defineMetadata(INJECTION_TOKEN_METADATA_KEY, injectionTokensMetadata, wrapper);

        return wrapper;
    }) as ClassDecorator;
}

Caveat is that I have to register MyDecorator below the tsyringe one, so that tsyringe registers my overriden constructor reference. For example:

@singleton()
@MyDecorator()
export class MyService implements IMyService {

    constructor(
        @inject('MyOtherService') private _myOtherService: IMyOtherService
    ) {
    }
}

And then I’m doing

// registration
container.register('MyService', MyService);

// resolution somewhere else
container.resolve<IMyService>('MyService');
1reaction
lrembaczcommented, Dec 31, 2019

@skiptirengu, @user753 Had the same issue but only when I was using @babel/typescript presets. When I changed it to ts-loader issue dissapeared.

It’s probably because resolving of decorators is other in both cases.

Code from injectable decorator passed with param inject decorator is no more giiving errors and getting resolved.

export function fixedInject(token: InjectionToken<any>): (target: any, propertyKey: string | symbol, parameterIndex: number) => any {
    return (target: any, propertyKey: string | symbol, parameterIndex: number) => {
        inject(token)(target, propertyKey, parameterIndex);
        const params = Reflect.getMetadata("design:paramtypes", target) || [];
        const injectionTokens = Reflect.getOwnMetadata("injectionTokens", target) || {};
        Object.keys(injectionTokens).forEach(function (key) {
            params[+key] = injectionTokens[key];
        });
    }
}

After some tries I’ve managed that generating keys for injectionTokens is working. It’s for sure related to babel-plugin-transform-typescript-metadata and @babel/typescript.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Primer on Python Decorators
The other way to use decorators on classes is to decorate the whole class. This is, for example, done in the new dataclasses...
Read more >
Chain Multiple Decorators in Python - GeeksforGeeks
Example 1: For num() function we are applying 2 decorator functions. Firstly the inner decorator will work and then the outer decorator.
Read more >
Python Decorators (With Examples) - Programiz
In Python, a decorator is a design pattern that allows you to modify the functionality of a function by wrapping it in another...
Read more >
Python Decorators: From Simple Decorators to Nesting Multiple
The way to use parameters with decorator is by sending them after using @ symbol with the name of the decorator method. In...
Read more >
Python: how to use multiple decorators on one function
Decorators are a confusing Python topic, especially when you see two or more used at once! Here's a simple explanation of what's going...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found