Advertisement
Guest User

Untitled

a guest
Jul 18th, 2019
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.24 KB | None | 0 0
  1. import {
  2. BadRequestException,
  3. Injectable,
  4. NotFoundException,
  5. } from '@nestjs/common';
  6. import { Repository } from 'typeorm';
  7.  
  8. @Injectable()
  9. export class CrudService<T> {
  10. constructor(protected readonly repository: Repository<T>) {}
  11.  
  12. public async getById(id: number): Promise<T> {
  13. try {
  14. return await this.repository.findOne(id);
  15. } catch (error) {
  16. throw new NotFoundException();
  17. }
  18. }
  19.  
  20. public async create(entity: T): Promise<T> {
  21. try {
  22. const instance = await this.repository.create(entity);
  23. return await this.repository.save(instance);
  24. } catch (error) {
  25. throw new BadRequestException(error.message);
  26. }
  27. }
  28.  
  29. public async update(id: number, entity: T): Promise<T> {
  30. try {
  31. const entityToUpdate = await this.repository.findOne(id);
  32.  
  33. Object.entries(entity).map(([key, value]) => {
  34. entityToUpdate[key] = value;
  35. });
  36.  
  37. return await this.repository.save(entityToUpdate);
  38. } catch (error) {
  39. throw new BadRequestException(error.message);
  40. }
  41. }
  42.  
  43. public async delete(id: number): Promise<void> {
  44. try {
  45. await this.repository.delete(id);
  46. } catch (error) {
  47. throw new NotFoundException();
  48. }
  49. }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement