@ibabkin/utils
v0.1.0
Published
Utilities
Downloads
14
Readme
Install
npm install @ibabkin/utils reflect-metadata
yarn add @ibabkin/utils reflect-metadata
tsconfig.json
{
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true
}
}
Usage
import { inject, resolve } from "@ibabkin/utils";
class Logger {
constructor(@inject(context => context.topic) private name: string) {
}
}
const logger = resolve({topic: 'main'})(Logger);
Hooks
import { hook, getHooks } from "@ibabkin/utils";
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 "@ibabkin/utils";
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");
}
}