|
| 1 | +import { Service } from 'typedi'; |
| 2 | +import { OrmRepository } from 'typeorm-typedi-extensions'; |
| 3 | +import { PetRepository } from '../repositories/PetRepository'; |
| 4 | +import { Pet } from '../models/Pet'; |
| 5 | +import { events } from '../subscribers/events'; |
| 6 | +import { EventDispatcher, EventDispatcherInterface } from '../../decorators/EventDispatcher'; |
| 7 | +import { Logger, LoggerInterface } from '../../decorators/Logger'; |
| 8 | + |
| 9 | + |
| 10 | +@Service() |
| 11 | +export class PetService { |
| 12 | + |
| 13 | + constructor( |
| 14 | + @OrmRepository() private petRepository: PetRepository, |
| 15 | + @EventDispatcher() private eventDispatcher: EventDispatcherInterface, |
| 16 | + @Logger(__filename) private log: LoggerInterface |
| 17 | + ) { } |
| 18 | + |
| 19 | + public find(): Promise<Pet[]> { |
| 20 | + this.log.info('Find all pets'); |
| 21 | + return this.petRepository.find(); |
| 22 | + } |
| 23 | + |
| 24 | + public findOne(id: string): Promise<Pet | undefined> { |
| 25 | + this.log.info('Find all pets'); |
| 26 | + return this.petRepository.findOne({ id }); |
| 27 | + } |
| 28 | + |
| 29 | + public async create(pet: Pet): Promise<Pet> { |
| 30 | + this.log.info('Create a new pet => ', pet.toString()); |
| 31 | + const newPet = await this.petRepository.save(pet); |
| 32 | + this.eventDispatcher.dispatch(events.pet.created, newPet); |
| 33 | + return newPet; |
| 34 | + } |
| 35 | + |
| 36 | + public update(id: string, pet: Pet): Promise<Pet> { |
| 37 | + this.log.info('Update a pet'); |
| 38 | + pet.id = id; |
| 39 | + return this.petRepository.save(pet); |
| 40 | + } |
| 41 | + |
| 42 | + public delete(id: string): Promise<void> { |
| 43 | + this.log.info('Delete a pet'); |
| 44 | + return this.petRepository.removeById(id); |
| 45 | + } |
| 46 | + |
| 47 | +} |
0 commit comments