base controller + base service added

This commit is contained in:
sdraris 2025-08-25 10:32:20 +02:00
parent 47ccbb61f7
commit 4dba85bb18
2 changed files with 61 additions and 0 deletions

View File

@ -0,0 +1,33 @@
import { Body, Delete, Get, Param, Patch, Post } from "@nestjs/common";
import { BaseService } from "./base.service";
import type { DeepPartial, ObjectLiteral } from "typeorm";
import type { QueryDeepPartialEntity } from "typeorm/query-builder/QueryPartialEntity.js";
export class BaseController<T extends ObjectLiteral> {
constructor(protected readonly service: BaseService<T>) { }
@Get()
getAll(relations: string[] = []) {
return this.service.findAll(relations);
}
@Get(':id')
getOne(@Param('id') id: string) {
return this.service.findOne(id);
}
@Post()
create(@Body() data: DeepPartial<T>) {
return this.service.create(data);
}
@Patch(':id')
update(@Param('id') id: string, @Body() data: QueryDeepPartialEntity<T>) {
return this.service.update(id, data);
}
@Delete(':id')
delete(@Param('id') id: string) {
return this.service.delete(id);
}
}

View File

@ -0,0 +1,28 @@
import { DeepPartial, ObjectLiteral, Repository } from "typeorm";
import { QueryDeepPartialEntity } from "typeorm/query-builder/QueryPartialEntity.js";
export class BaseService<T extends ObjectLiteral> {
constructor(protected readonly repo: Repository<T>) { }
findAll(relations: string[] = []) {
return this.repo.find({ relations });
}
findOne(id: string, relations: string[] = []) {
return this.repo.findOne({ where: { id } as any, relations });
}
create(data: DeepPartial<T>) {
const entity = this.repo.create(data);
return this.repo.save(entity);
}
async update(id: string, data: QueryDeepPartialEntity<T>) {
await this.repo.update(id, data);
return this.findOne(id);
}
delete(id: string) {
return this.repo.delete(id);
}
}