|
| 1 | +import { Injectable, Logger, OnModuleInit } from '@nestjs/common'; |
| 2 | +import Crisp from 'crisp-api'; |
| 3 | +import { EVENT_NAME } from 'src/crisp/crisp.interface'; |
| 4 | +import { CrispService } from 'src/crisp/crisp.service'; |
| 5 | +import { CrispEventDto } from 'src/crisp/dtos/crisp.dto'; |
| 6 | +import { crispPluginId, crispPluginKey } from 'src/utils/constants'; |
| 7 | +const CrispClient = new Crisp(); |
| 8 | +const logger = new Logger('CrispLogger'); |
| 9 | + |
| 10 | +// This service is split from CrispService due to CrispService being imported/initiated multiple times |
| 11 | +// To avoid creating duplicate listeners and events, this CrispListenerService was decoupled |
| 12 | +@Injectable() |
| 13 | +export class CrispListenerService implements OnModuleInit { |
| 14 | + constructor(private crispService: CrispService) { |
| 15 | + CrispClient.authenticateTier('plugin', crispPluginId, crispPluginKey); |
| 16 | + } |
| 17 | + |
| 18 | + onModuleInit() { |
| 19 | + logger.log(`Crisp service initiated`); |
| 20 | + |
| 21 | + try { |
| 22 | + const handleCrispEvent = async (message, eventName) => |
| 23 | + await this.crispService.handleCrispEvent(message, eventName); |
| 24 | + |
| 25 | + CrispClient.on('message:send', async function (message: CrispEventDto) { |
| 26 | + handleCrispEvent(message, EVENT_NAME.CHAT_MESSAGE_SENT); |
| 27 | + }) |
| 28 | + .then(function () { |
| 29 | + logger.log('Crisp service listening to sent messages'); |
| 30 | + }) |
| 31 | + .catch(function (error) { |
| 32 | + logger.error('Crisp service failed listening to sent messages:', error); |
| 33 | + }); |
| 34 | + |
| 35 | + CrispClient.on('message:received', function (message: CrispEventDto) { |
| 36 | + handleCrispEvent(message, EVENT_NAME.CHAT_MESSAGE_RECEIVED); |
| 37 | + }) |
| 38 | + .then(function () { |
| 39 | + logger.log('Crisp service listening to received messages'); |
| 40 | + }) |
| 41 | + .catch(function (error) { |
| 42 | + logger.error('Crisp service failed listening to sent messages:', error); |
| 43 | + }); |
| 44 | + } catch (error) { |
| 45 | + logger.error('Crisp service failed to initiate:', error); |
| 46 | + } |
| 47 | + } |
| 48 | +} |
0 commit comments