-
Notifications
You must be signed in to change notification settings - Fork 0
/
sms-api.service.ts
90 lines (85 loc) · 2.76 KB
/
sms-api.service.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import { HttpStatus, Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { v4 as uuidv4 } from 'uuid';
import {
ApiKey,
NotificationLog,
RK_NOTIFICATION_SMS,
RabbitmqService,
User,
} from '@app/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { SmsInputDto } from './dtos/sms.dto';
interface smsLog {
_id: string;
readonly channel: string;
readonly status: string;
readonly message: string;
readonly sender: string;
readonly recipient: string[];
readonly scheduleDate: Date;
readonly secretKey: string;
readonly user: {
readonly userId: string;
readonly organisationId: string;
};
}
@Injectable()
export class SmsApiService {
constructor(
private readonly rabbitMQService: RabbitmqService,
@InjectModel(NotificationLog.name)
private notificationLogModel: Model<NotificationLog>,
@InjectRepository(ApiKey, 'postgres')
private apiKeyRepo: Repository<ApiKey>,
@InjectRepository(User, 'postgres')
private userRepo: Repository<User>,
) {}
async publishSMS(body: SmsInputDto, secretKey: string) {
let _id = uuidv4();
const payload = { _id, ...body };
try {
const response = await this.rabbitMQService.publish(
RK_NOTIFICATION_SMS,
payload,
);
const { userId } = await this.apiKeyRepo.findOneBy({ secretKey });
const { organisationId } = await this.userRepo.findOne({
where: { userId },
});
const log: smsLog = {
_id,
channel: 'SMS',
status: response === true ? 'QUEUING' : 'QUEUE FAIL',
message: body.body,
sender: body.sender,
recipient: body.recipient,
scheduleDate: new Date(),
secretKey,
user: {
userId,
organisationId,
},
};
const notificationLog = new this.notificationLogModel(log);
await notificationLog.save();
if (response === false) {
return {
status: HttpStatus.INTERNAL_SERVER_ERROR,
message: 'SMS failed to add to the queue',
};
}
return {
status: HttpStatus.CREATED,
message: 'SMS added to the queue successfully',
};
} catch (error) {
return {
status: HttpStatus.INTERNAL_SERVER_ERROR,
message: 'Something went wrong',
};
}
}
}