diff --git a/src/common/base.controller.ts b/src/common/base.controller.ts new file mode 100644 index 0000000..d1d3224 --- /dev/null +++ b/src/common/base.controller.ts @@ -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 { + constructor(protected readonly service: BaseService) { } + + @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) { + return this.service.create(data); + } + + @Patch(':id') + update(@Param('id') id: string, @Body() data: QueryDeepPartialEntity) { + return this.service.update(id, data); + } + + @Delete(':id') + delete(@Param('id') id: string) { + return this.service.delete(id); + } +} \ No newline at end of file diff --git a/src/common/base.service.ts b/src/common/base.service.ts new file mode 100644 index 0000000..90917b4 --- /dev/null +++ b/src/common/base.service.ts @@ -0,0 +1,28 @@ +import { DeepPartial, ObjectLiteral, Repository } from "typeorm"; +import { QueryDeepPartialEntity } from "typeorm/query-builder/QueryPartialEntity.js"; + +export class BaseService { + constructor(protected readonly repo: Repository) { } + + 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) { + const entity = this.repo.create(data); + return this.repo.save(entity); + } + + async update(id: string, data: QueryDeepPartialEntity) { + await this.repo.update(id, data); + return this.findOne(id); + } + + delete(id: string) { + return this.repo.delete(id); + } +} \ No newline at end of file