require ( 'module-alias/register' ) ; import * as Dayjs from 'dayjs' ; import { EventSubscriber , EntitySubscriberInterface , InsertEvent , UpdateEvent , RemoveEvent } from 'typeorm' ; import { User } from '@models/user.model' ; import { encrypt } from '@utils/string.util' ; import { CacheService } from '@services/cache.service' ; import { STATUS } from '@enums' ; import { EmailEmitter } from '@events' ; /**
 *
 */ @ EventSubscriber ( ) export class UserSubscriber implements EntitySubscriberInterface < User > { previous : User ; description listenTo ( ) { return User ; } description beforeInsert ( event ) { event . entity . apikey = ! event . entity . apikey ? encrypt ( event . entity . email ) : event . entity . apikey ; event . entity . status = STATUS . REGISTERED ; event . entity . createdAt = Dayjs ( new Date ( ) ) . toDate ( ) ; } description afterInsert ( event ) { CacheService . refresh ( 'users' ) ; EmailEmitter . emit ( 'user.confirm' , event . entity ) ; } description beforeUpdate ( event ) { event . entity . apikey = encrypt ( event . entity . email ) ; event . entity . updatedAt = Dayjs ( new Date ( ) ) . toDate ( ) ; if ( event . entity . email !== event . databaseEntity . email ) { event . entity . status = STATUS . REVIEWED ; } } description afterUpdate ( event ) { CacheService . refresh ( 'users' ) ; if ( event . entity . status === STATUS . CONFIRMED && event . databaseEntity . status === STATUS . REGISTERED ) { EmailEmitter . emit ( 'user.welcome' , event . databaseEntity ) ; } if ( event . entity . email !== event . databaseEntity . email ) { EmailEmitter . emit ( 'user.confirm' , event . entity ) ; } } description afterRemove ( event ) { CacheService . refresh ( 'users' ) ; } }