Files
PDV/apps/api/src/common/base.service.ts
2026-09-30 14:45:10 -05:00

55 lines
1.4 KiB
TypeScript

import { NotFoundException } from "@nestjs/common";
import type { IRepository } from "./repository.interface.js";
import type { IService } from "./service.interface.js";
/**
* Generic business layer: delegates to an `IRepository`, translating a
* missing row into a `NotFoundException`. Subclasses may override
* `notFoundMessage` for a more specific error message.
*/
export abstract class BaseService<
T,
CreateInput,
UpdateInput,
WhereKey,
> implements IService<T, CreateInput, UpdateInput, WhereKey> {
constructor(
protected readonly repository: IRepository<
T,
CreateInput,
UpdateInput,
WhereKey
>,
) {}
findAll(): Promise<T[]> {
return this.repository.findAll();
}
async findById(where: WhereKey): Promise<T> {
const entity = await this.repository.findById(where);
if (!entity) {
throw new NotFoundException(this.notFoundMessage(where));
}
return entity;
}
create(data: CreateInput): Promise<T> {
return this.repository.create(data);
}
async update(where: WhereKey, data: UpdateInput): Promise<T> {
await this.findById(where);
return this.repository.update(where, data);
}
async delete(where: WhereKey): Promise<void> {
await this.findById(where);
await this.repository.delete(where);
}
protected notFoundMessage(where: WhereKey): string {
return `Resource not found: ${JSON.stringify(where)}`;
}
}