ts-constructor-injector
v5.0.9
Published
Injector
Downloads
56
Readme
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");
}
}