11import { singleton } from 'tsyringe' ;
2- import { Event } from '../entities/Event' ;
2+ import { Event , APIEvent } from '../entities/Event' ;
33import { getRepository , getConnection } from 'typeorm' ;
44import { validateOrReject } from 'class-validator' ;
5+ import { EventChannel } from '../entities/Channel' ;
56import { formatValidationErrors , APIError , HttpCode } from '../util/errors' ;
67
7- type EventCreationData = Omit < Event , 'id' > ;
8+ type EventCreationData = Omit < APIEvent , 'id' | 'channelID '> ;
89
910enum PatchEventError {
1011 IdMissing = 'Event ID missing' ,
@@ -13,25 +14,28 @@ enum PatchEventError {
1314
1415@singleton ( )
1516export default class EventService {
16- public async createEvent ( data : EventCreationData ) : Promise < Event > {
17+ public async createEvent ( data : EventCreationData ) : Promise < APIEvent > {
1718 const event = new Event ( ) ;
1819 const { title, description, startTime, endTime, external } = data ;
19- Object . assign ( event , { title, description, startTime, endTime, external } ) ;
20+ Object . assign ( event , { title, description, startTime : new Date ( startTime ) , endTime : new Date ( endTime ) , external } ) ;
2021 await validateOrReject ( event ) . catch ( e => Promise . reject ( formatValidationErrors ( e ) ) ) ;
21- return getRepository ( Event ) . save ( event ) ;
22+ const channel = new EventChannel ( ) ;
23+ channel . event = event ;
24+ event . channel = channel ;
25+ return ( await getRepository ( Event ) . save ( event ) ) . toJSON ( ) ;
2226 }
2327
24- public findAll ( ) : Promise < Event [ ] > {
25- return getRepository ( Event ) . find ( ) ;
28+ public async findAll ( ) : Promise < APIEvent [ ] > {
29+ return ( await getRepository ( Event ) . find ( ) ) . map ( event => event . toJSON ( ) ) ;
2630 }
2731
28- public async editEvent ( data : Pick < Event , 'id' > & Partial < Event > ) : Promise < Event > {
32+ public async editEvent ( data : Pick < Event , 'id' > & Partial < Event > ) : Promise < APIEvent > {
2933 return getConnection ( ) . transaction ( async entityManager => {
3034 if ( ! data . id ) throw new APIError ( HttpCode . BadRequest , PatchEventError . IdMissing ) ;
3135 const event = await entityManager . findOneOrFail ( Event , data . id ) . catch ( ( ) => Promise . reject ( new APIError ( HttpCode . BadRequest , PatchEventError . EventNotFound ) ) ) ;
32- Object . assign ( event , data ) ;
36+ Object . assign ( event , { ... data , channel : event . channel } ) ;
3337 await validateOrReject ( event ) . catch ( e => Promise . reject ( formatValidationErrors ( e ) ) ) ;
34- return entityManager . save ( event ) ;
38+ return ( await entityManager . save ( event ) ) . toJSON ( ) ;
3539 } ) ;
3640 }
3741}
0 commit comments