ts-constructor-injector
TypeScript icon, indicating that this package has built-in type declarations

5.0.9 • Public • Published

NPM version:latest npm downloads npm bundle size (minified + gzip) Coverage Status License

ts-constructor-injector

Dependency injection for typescript classes

Install

npm install ts-constructor-injector reflect-metadata
yarn add ts-constructor-injector reflect-metadata

tsconfig.json

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

Usage

import { inject, resolve } from "ts-constructor-injector";

class Logger {
  constructor(@inject(context => context.topic) private name: string) {
  }
}

const logger = resolve({topic: 'main'})(Logger);

Hooks

import { hook, getHooks } from "ts-constructor-injector";

class Logger {
  @hook('onDispose')
  async dispose(message: string): Promise<void> {
    console.log(message);
  }
}

(async () => {
  const instance = new Logger();
  for (const hook of getHooks(instance, 'onDispose')) {
    await instance[hook]('disposed'); // disposed
  }
})()

ErrorHandler

import { handleAsyncError } from "ts-constructor-injector";

const prismaToDomainError: HandleErrorParams = (error, context) => {
  if (error instanceof Prisma.PrismaClientKnownRequestError) {
    switch (error.code) {
      case "P2002":
        throw new PersistenceConflictError(errorToString(error));
      case "P2025":
        throw new EntityNotFoundError(errorToString(error));
      default:
        throw new PersistenceError(errorToString(error));
    }
  }

  throw new UnknownError(errorToString(error));
};

class AsyncRepo {
  @handleAsyncError(prismaToDomainError)
  async saveSmth() {
    await sleep(1000);
    throw new Prisma.PrismaClientKnownRequestError("P2002");
  }
}

class Repo {
  @handleError(prismaToDomainError)
  saveSmth() {
    throw new Prisma.PrismaClientKnownRequestError("P2002");
  }
}

Dependents (0)

Package Sidebar

Install

npm i ts-constructor-injector

Weekly Downloads

5

Version

5.0.9

License

ISC

Unpacked Size

52.9 kB

Total Files

62

Last publish

Collaborators

  • igorbabkin