import { config, SNS, SQS } from 'aws-sdk' import { OnModuleInit, Injectable } from '@nestjs/common' import { debug, Debugger } from 'debug' import { nanoid } from 'nanoid' import { PhoneUtils } from '../../utils/phone.utils' import { SMSArgs } from '../../models/types' @Injectable() export class AwsService implements OnModuleInit { private debug: Debugger = debug(`http:${this.constructor.name}`) private _SNS: SNS private _SQS: SQS onModuleInit(): void { config.update({ region: process.env.AWS_SNS_REGION, }) this._SNS = new SNS({ apiVersion: '2010-03-31' }) this._SQS = new SQS({ apiVersion: '2012-11-05' }) } async sendSMS(args: SMSArgs): Promise { const options = { Message: args.message, PhoneNumber: PhoneUtils.toE164(args.phoneNumber), } const id = nanoid() this.debug.extend('request')(JSON.stringify({ id, type: 'publish_sns', body: { ...options } })) const response = await this._SNS.publish(options).promise() this.debug.extend('response')(JSON.stringify({ id, type: 'publish_sns', response })) } async sendSQS(args: SQS.SendMessageRequest): Promise { const id = nanoid() this.debug.extend('request')(JSON.stringify({ id, type: 'send_sqs', body: { ...args } })) const response = await this._SQS.sendMessage(args).promise() this.debug.extend('response')(JSON.stringify({ id, type: 'send_sqs', response })) } async deleteSQSMessage(QueueUrl: string, ReceiptHandle: string): Promise { const id = nanoid() this.debug.extend('request')(JSON.stringify({ id, type: 'delete_sqs', body: { QueueUrl, ReceiptHandle } })) const response = await this._SQS.deleteMessage({ QueueUrl, ReceiptHandle }).promise() this.debug.extend('response')(JSON.stringify({ id, type: 'delete_sqs', response })) } }