1.0.0-rc.4 • Published 3 years ago

@typemon/metadata v1.0.0-rc.4

Weekly downloads
57
License
MIT
Repository
gitlab
Last release
3 years ago

Metadata - version license typescript-version gitlab-pipeline coverage

  • Provides highly abstracted metadata management functions
  • Support inheritance and parameter metadata
  • Fully integrated with decorators

Installation

$ npm install @typemon/metadata reflect-metadata

TypeScript

Configure metadata and decorator options.

{
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true
}

Reflect Metadata

Import only once at the application entry point.

import 'reflect-metadata';

Usage

I don't think I need an explanation.

const metadata: Metadata = Metadata.of({
    target,
    propertyKey?,
    parameterIndex?,
});

metadata.set(key, value);
metadata.get(key, value);
metadata.delete(key);

This is recommended for a one-time operation.

Metadata.set({
    target,
    propertyKey?,
    parameterIndex?,
    key,
    value,
});

Parameter Metadata

In the same way, you can easily manage parameter metadata as well.

  • Inheritance is supported just like regular metadata.
  • If possible, the design:type metadata is set.
@Decorator()
class Parent {
    public constructor(
        public readonly parameter: string,
    ) { }
}

@Decorator()
class Child extends Parent { }

const child: Metadata = Metadata.of({
    target: Child,
    parameterIndex: 0,
});
const parent: Metadata = Metadata.of({
    target: Parent,
    parameterIndex: 0,
});

expect(child.parent).toBe(parent);
expect(child.get('design:type')).toBe(String);
expect((): void => child.getOwn('design:type')).toThrow(MetadataDoesNotExistError);

Decorator

You can easily create decorators, and basically decorate them everywhere.

function Decorator(...parameters: any): Metadata.Decorator {
    return Metadata.decorator((metadata: Metadata): void => {
        ...
    });
}

@Decorator(key, value)
class Example {
    @Decorator(key, value)
    public static property: unknown;

    @Decorator(key, value)
    public static method(
        @Decorator(key, value)
        parameter: unknown,
    ): void { }

    @Decorator(key, value)
    public property: unknown;

    public constructor(
        @Decorator(key, value)
        parameter: unknown,
    ) { }

    @Decorator(key, value)
    public method(
        @Decorator(key, value)
        parameter: unknown,
    ): void { }
}

You can limit the type.

function Decorator(...parameters: any): ClassDecorator {
    return Metadata.decorator((metadata: Metadata): void => {
        ...
    });
}

You can combine types.

function Decorator(...parameters: any): PropertyDecorator & MethodDecorator {
    return Metadata.decorator((metadata: Metadata): void => {
        ...
    });
}

You can also decorate dynamically.

Metadata.decorate({
    target,
    propertyKey?,
    parameterIndex?,
    decorators,
});