Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import {
- BadRequestException,
- Injectable,
- NotFoundException,
- } from '@nestjs/common';
- import { Repository } from 'typeorm';
- @Injectable()
- export class CrudService<T> {
- constructor(protected readonly repository: Repository<T>) {}
- public async getById(id: number): Promise<T> {
- try {
- return await this.repository.findOne(id);
- } catch (error) {
- throw new NotFoundException();
- }
- }
- public async create(entity: T): Promise<T> {
- try {
- const instance = await this.repository.create(entity);
- return await this.repository.save(instance);
- } catch (error) {
- throw new BadRequestException(error.message);
- }
- }
- public async update(id: number, entity: T): Promise<T> {
- try {
- const entityToUpdate = await this.repository.findOne(id);
- Object.entries(entity).map(([key, value]) => {
- entityToUpdate[key] = value;
- });
- return await this.repository.save(entityToUpdate);
- } catch (error) {
- throw new BadRequestException(error.message);
- }
- }
- public async delete(id: number): Promise<void> {
- try {
- await this.repository.delete(id);
- } catch (error) {
- throw new NotFoundException();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement