forked from Ynov/ptitspas-ynov-back
base controller + base service added
This commit is contained in:
parent
47ccbb61f7
commit
4dba85bb18
33
src/common/base.controller.ts
Normal file
33
src/common/base.controller.ts
Normal 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
28
src/common/base.service.ts
Normal file
28
src/common/base.service.ts
Normal 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
x
Reference in New Issue
Block a user