@andrewcaires/decorator
v1.2.2
Published
Typescript decorator library for nodejs development
Maintainers
Readme
@andrewcaires/decorator
TypeScript decorator utilities for Node.js applications.
This package provides small decorators and helpers for constructor injection, singleton classes, trait-style prototype composition, and metadata storage.
Installation
npm i @andrewcaires/decoratorTypeScript Setup
This library uses TypeScript decorators. Enable decorators in your tsconfig.json:
{
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true
}
}Imports
import {
Inject,
Injectable,
Singleton,
Trait,
getInjectionArgs,
isClassMethodDecoratorContext,
metadata,
} from "@andrewcaires/decorator";Injectable
Injectable() creates a class decorator that resolves constructor dependencies registered with Inject().
import { Inject, Injectable } from "@andrewcaires/decorator";
@Injectable()
class Logger {
info(message: string): void {
console.log(message);
}
}
@Injectable()
class UserService {
constructor(@Inject(Logger) private readonly logger: Logger) {}
create(): void {
this.logger.info("User created");
}
}
const service = new UserService();
service.create();Injected dependencies are resolved before manual constructor arguments.
@Injectable()
class UserService {
constructor(
@Inject(Logger) private readonly logger: Logger,
private readonly name: string,
) {}
}
const service = new UserService("Andrew");In the example above, Logger is injected and "Andrew" is passed as the next constructor argument.
Inject
Inject(key) creates a parameter decorator for constructor dependency injection.
class Repository {}
@Injectable()
class Service {
constructor(@Inject(Repository) private readonly repository: Repository) {}
}Dependencies are sorted by the original parameter index, so multiple injected parameters keep the same order as the constructor signature.
class Config {}
class Logger {}
@Injectable()
class Service {
constructor(
@Inject(Config) private readonly config: Config,
@Inject(Logger) private readonly logger: Logger,
) {}
}getInjectionArgs
getInjectionArgs(target) returns the resolved dependency instances for a class constructor.
It is used internally by Injectable(), but it is exported if you need to inspect or manually resolve constructor dependencies.
class Logger {}
class Service {
constructor(public readonly logger: Logger) {}
}
Inject(Logger)(Service, undefined, 0);
const args = getInjectionArgs(Service);
const service = new Service(...args);Resolved dependency instances are cached in metadata and reused for subsequent resolutions.
Singleton
Singleton() creates a class decorator that always returns the first created instance of the decorated class.
import { Singleton } from "@andrewcaires/decorator";
@Singleton()
class ConfigService {
public readonly createdAt = Date.now();
}
const first = new ConfigService();
const second = new ConfigService();
console.log(first === second); // trueOnly the first constructor call initializes the instance. Later calls return the stored instance.
Trait
Trait(...constructors) copies prototype members from one or more classes to the decorated class.
import { Trait } from "@andrewcaires/decorator";
class CanGreet {
greet(): string {
return "hello";
}
}
@Trait(CanGreet)
class Person {}
const person = new Person() as Person & CanGreet;
console.log(person.greet()); // helloThe source class constructor property is not copied.
When multiple traits define the same property name, later traits overwrite earlier descriptors.
metadata
metadata(key, target, value) stores and returns metadata by symbol key and owner.
The owner can be a class constructor, an object instance, or a symbol.
import { metadata } from "@andrewcaires/decorator";
const key = Symbol("settings");
class Service {}
const settings = metadata(key, Service, { enabled: true });
const sameSettings = metadata(key, new Service(), { enabled: false });
console.log(settings === sameSettings); // true
console.log(sameSettings.enabled); // trueThe first value stored for a given key and owner is preserved, including falsy values such as false, 0, and "".
const key = Symbol("flag");
const owner = Symbol("owner");
metadata(key, owner, false);
console.log(metadata(key, owner, true)); // falseisClassMethodDecoratorContext
isClassMethodDecoratorContext(value) is a type guard for standard class method decorator contexts.
import { isClassMethodDecoratorContext } from "@andrewcaires/decorator";
function decorator(value: unknown, context: unknown): void {
if (isClassMethodDecoratorContext(context)) {
console.log(context.kind); // method
console.log(context.name);
}
}It returns true when the value is an object with:
kindequal to"method"nameaddInitializer
Exported Keys And Types
The package also exports internal symbols and types used by the decorators:
InjectionInjectionKeySingletonKey
These are mainly useful for advanced integrations or tests.
API Reference
const Inject: (key: TypeAnyConstructor) => ParameterDecorator;
const Injectable: <T extends TypeAnyConstructor>() => TypeAnyFunction<T>;
const getInjectionArgs: (target: TypeAnyConstructor) => Array<any>;
const Singleton: <T extends TypeAnyConstructor>() => TypeAnyFunction<T>;
const Trait: (...constructors: Array<TypeAnyConstructor>) => ClassDecorator;
const metadata: <T = unknown>(key: symbol, target: object | symbol, value: T) => T;
const isClassMethodDecoratorContext: (value: unknown) => value is ClassMethodDecoratorContext;Scripts
npm test
npm run lint
npm run build