aeremmiddleware 1.0.2 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,99 +1,96 @@
1
- interface WhatsAppMessageData {
2
- from: string;
3
- to: string;
4
- body?: string;
5
- content?: WhatsappContentType;
6
- }
7
-
8
- interface Templatetype {
9
- name: string;
10
- language: {
11
- policy: string;
12
- code: string;
13
- };
14
- components: Array<{
15
- type: string;
16
- parameters: Array<{
17
- type: string;
18
- text: string;
19
- }>;
20
- }>;
21
- }
22
- interface WhatsappContentType {
23
- type: string; //"text", "document", "image", "video", "template";
24
- text?: { preview_url: string; body: string };
25
- document?: any;
26
- image?: any;
27
- video?: any;
28
- recipient_type: any;
29
- template?: Templatetype;
30
- }
31
-
32
- export interface DemoBody {
33
- whatsapp: {
34
- messages: Array<WhatsAppMessageData>;
35
- };
36
- }
37
-
38
- interface WhatsAppTemplateMessage {
39
- from: string;
40
- to: string;
41
- content: {
42
- type: string;
43
- template: {
44
- name: string;
45
- language: {
46
- policy?: string;
47
- code: string;
48
- };
49
- components: Array<{
50
- type: string;
51
- parameters: Array<{
52
- type: string;
53
- text: string;
54
- }>;
55
- }>;
56
- };
57
- };
58
- }
59
-
60
- export interface WhatsAppTemplateDemoBody {
61
- whatsapp: {
62
- messages: Array<WhatsAppTemplateMessage>;
63
- };
64
- }
65
-
66
- export interface EmiReminderAug2023 {
67
- code: number;
68
- error_data: null;
69
- status: string;
70
- data: {
71
- waba_id: string;
72
- name: string;
73
- components: Array<HeaderComponent | BodyComponent>;
74
- };
75
- }
76
-
77
- interface HeaderComponent {
78
- type: string;
79
- format: string;
80
- text: string;
81
- example: {
82
- header_text: Array<string>;
83
- };
84
- }
85
- interface BodyComponent {
86
- type: string;
87
- text: string;
88
- example: {
89
- body_text: Array<Array<string>>;
90
- };
91
- }
92
- export interface SmsDemoBody{
93
- To:string,
94
- Body:string,
95
- }
96
- export enum Provider {
97
- EXOTEL = "EXOTEL",
98
- GUPSHUP = "GUPSHUP",
1
+ interface WhatsAppMessageData {
2
+ from: string;
3
+ to: string;
4
+ body?: string;
5
+ content?: WhatsappContentType;
6
+ }
7
+
8
+ interface Templatetype {
9
+ name: string;
10
+ language: {
11
+ policy: string;
12
+ code: string;
13
+ };
14
+ components: Array<{
15
+ type: string;
16
+ parameters: Array<{
17
+ type: string;
18
+ text: string;
19
+ }>;
20
+ }>;
21
+ }
22
+ interface WhatsappContentType {
23
+ type: string; //"text", "document", "image", "video", "template";
24
+ text?: { preview_url: string; body: string };
25
+ document?: any;
26
+ image?: any;
27
+ video?: any;
28
+ recipient_type: any;
29
+ template?: Templatetype;
30
+ }
31
+
32
+ export interface DemoBody {
33
+ whatsapp: {
34
+ messages: Array<WhatsAppMessageData>;
35
+ };
36
+ }
37
+
38
+ interface WhatsAppTemplateMessage {
39
+ from: string;
40
+ to: string;
41
+ content: {
42
+ type: string;
43
+ template: {
44
+ name: string;
45
+ language: {
46
+ policy?: string;
47
+ code: string;
48
+ };
49
+ components: Array<{
50
+ type: string;
51
+ parameters: Array<{
52
+ type: string;
53
+ text: string;
54
+ }>;
55
+ }>;
56
+ };
57
+ };
58
+ }
59
+
60
+ export interface WhatsAppTemplateDemoBody {
61
+ whatsapp: {
62
+ messages: Array<WhatsAppTemplateMessage>;
63
+ };
64
+ }
65
+
66
+ export interface EmiReminderAug2023 {
67
+ code: number;
68
+ error_data: null;
69
+ status: string;
70
+ data: {
71
+ waba_id: string;
72
+ name: string;
73
+ components: Array<HeaderComponent | BodyComponent>;
74
+ };
75
+ }
76
+
77
+ interface HeaderComponent {
78
+ type: string;
79
+ format: string;
80
+ text: string;
81
+ example: {
82
+ header_text: Array<string>;
83
+ };
84
+ }
85
+ interface BodyComponent {
86
+ type: string;
87
+ text: string;
88
+ example: {
89
+ body_text: Array<Array<string>>;
90
+ };
91
+ }
92
+
93
+ export enum Provider {
94
+ EXOTEL = "EXOTEL",
95
+ GUPSHUP = "GUPSHUP",
99
96
  }
@@ -1,6 +1,7 @@
1
- import Socials from './message'
2
-
3
- export const socials = {
4
- message : Socials,
5
-
1
+ import Socials from './whatsApp'
2
+ import Sms from './SmsSender'
3
+
4
+ export const socials = {
5
+ whatsapp : Socials,
6
+ text:Sms
6
7
  }
@@ -1,236 +1,188 @@
1
- import axios from "axios";
2
- import { DemoBody, EmiReminderAug2023,SmsDemoBody, Provider, WhatsAppTemplateDemoBody } from "./Whatsapp.types";
3
-
4
- class MessageSender {
5
- private exotelSid: string;
6
- private exotelToken: string;
7
- private exotelApiKey: string;
8
- private whatsappApiUrl!: string;
9
- private smsUrl!: string;
10
- private provider: string;
11
-
12
- constructor(payload: {
13
- exotelSid: string;
14
- exotelToken: string;
15
- exotelApiKey: string;
16
- provider: string;
17
- }) {
18
- const { exotelSid, exotelToken, exotelApiKey, provider } = payload;
19
- this.exotelSid = exotelSid;
20
- this.exotelToken = exotelToken;
21
- this.exotelApiKey = exotelApiKey;
22
- this.provider = provider;
23
-
24
- if (this.provider === Provider.EXOTEL) {
25
- this.whatsappApiUrl = `https://${exotelApiKey}:${exotelToken}@api.exotel.com/v2/accounts/${exotelSid}/messages`;
26
- this.smsUrl = `https://${exotelApiKey}:${exotelToken}@api.exotel.com/v1/Accounts/${exotelSid}/Sms/send`;
27
- } else if (this.provider === Provider.GUPSHUP) {
28
- // Define the URL for Gupshup API
29
- // this.gupshupApiUrl = ...;
30
- }
31
- }
32
-
33
- async getTemplates() {
34
- const request = await axios.get(
35
- `https://${this.exotelApiKey}:${this.exotelToken}@api.exotel.com/v2/accounts/${this.exotelSid}/templates?waba_id=114033855070320`
36
- );
37
-
38
- return request.data.response.whatsapp.templates;
39
- }
40
- getUniquePlaceholderCount(str: string) {
41
- const arr:Array<string> = [];
42
- str.split("{{").map((s) => arr.push(...s.split("}}")));
43
- const placeholders: Array<string> = arr.filter(
44
- (i) => i.match(/[0-9]+/) && !isNaN(Number(i))
45
- );
46
- return [...new Set(placeholders)].length;
47
- }
48
-
49
- validateTemplatePayload(template:EmiReminderAug2023, payload:any) {
50
- const templateComponents = template.data.components;
51
- if (templateComponents.length != 2) {
52
- return;
53
- }
54
-
55
- const [headerTemplate, bodyTemplate] = templateComponents;
56
- //this checks if placeholder is correct or not
57
- for (let index = 0; index < payload.whatsapp.messages.length; index++) {
58
- const message = payload.whatsapp.messages[index];
59
- const payloadComponents = message.content.template.components;
60
- for (let index2 = 0; index2 < payloadComponents.length; index2++) {
61
- const payloadComponent = payloadComponents[index2];
62
- // validate template header
63
- if (payloadComponent.type === headerTemplate.type.toLowerCase()) {
64
- const headerPlaceholdersCount = this.getUniquePlaceholderCount(
65
- headerTemplate.text
66
- );
67
- if (payloadComponent.parameters.length != headerPlaceholdersCount) {
68
- console.log("invalid header");
69
- throw new Error("header count mismatch");
70
- } else {
71
- // header validated
72
- // TODO: add more validations if required
73
- }
74
- } else if (payloadComponent.type === bodyTemplate.type.toLowerCase()) {
75
- const bodyPlaceholdersCount = this.getUniquePlaceholderCount(
76
- bodyTemplate.text
77
- );
78
- if (payloadComponent.parameters.length != bodyPlaceholdersCount) {
79
- console.log("invalid body");
80
- throw new Error("body count mismatch");
81
- } else {
82
- // validate template body
83
- // body validated
84
- // TODO: add more validations if required
85
- }
86
- }
87
- else
88
- throw new Error("type mismatch or incorrect")
89
-
90
- }
91
- return true;
92
- }
93
- }
94
- testType(obj: DemoBody) {
95
- let returnValue = true;
96
- obj.whatsapp.messages.every((message) => {
97
- returnValue =
98
- Boolean(message?.content?.type === "text" && message.content.text) ||
99
- Boolean(
100
- message?.content?.type === "document" && message.content.document
101
- ) ||
102
- Boolean(message?.content?.type === "image" && message.content.image) ||
103
- Boolean(message?.content?.type === "video" && message.content.video) ||
104
- Boolean(
105
- message?.content?.type === "template" && message.content.template
106
- );
107
- return returnValue;
108
- });
109
- return returnValue;
110
- }
111
-
112
- private async sendMessage(messageData: DemoBody): Promise<boolean> {
113
- try {
114
- let config = {
115
- method: "post",
116
- maxBodyLength: Infinity,
117
- url: this.whatsappApiUrl,
118
- headers: {
119
- "Content-Type": "application/json",
120
- },
121
-
122
- data: JSON.stringify(messageData),
123
- };
124
-
125
- const response = await axios.request(config);
126
- if (response.data.metadata && response.data.metadata.success != 0) {
127
- console.log("WhatsApp message sent successfully:", response.data);
128
- return true;
129
- } else {
130
- console.error("Error sending WhatsApp message:", response.data);
131
- return false;
132
- }
133
- } catch (error) {
134
- console.error("Error sending WhatsApp message:", error);
135
- return false;
136
- }
137
- }
138
-
139
- private async sendTemplateMessage(
140
- messageData: WhatsAppTemplateDemoBody
141
- ): Promise<boolean> {
142
- try {
143
- const config = {
144
- method: "post",
145
- maxBodyLength: Infinity,
146
- url: this.whatsappApiUrl,
147
- headers: {
148
- "Content-Type": "application/json",
149
- },
150
- data: JSON.stringify(messageData),
151
- };
152
-
153
- const response = await axios.request(config);
154
- if (response.data.metadata && response.data.metadata.success !== 0) {
155
- console.log(
156
- "WhatsApp template message sent successfully:",
157
- response.data
158
- );
159
- return true;
160
- } else {
161
- console.error(
162
- "Error sending WhatsApp template message:",
163
- response.data
164
- );
165
- return false;
166
- }
167
- } catch (error) {
168
- console.error("Error sending WhatsApp template message:", error);
169
- return false;
170
- }
171
- }
172
-
173
- private async sendOtpMessage(messageData: SmsDemoBody): Promise<boolean> {
174
-
175
- if(messageData.To && messageData.Body ){
176
- if(messageData.Body.length != 6){
177
- throw new Error("Please enter 6 digit number")
178
- }
179
- } else throw new Error("All input data not found")
180
-
181
- const bodyFormData=new FormData();
182
-
183
- const smsTemplateMsg="Your OTP for AEREMS login is %d. This %d will expire in 10 minutes."
184
-
185
- bodyFormData.append("To",messageData.To)
186
- bodyFormData.append("From","AEREM")
187
- bodyFormData.append("Body",smsTemplateMsg.replace(/%d/g,messageData.Body))
188
- bodyFormData.append("EncodingType","plain")
189
- bodyFormData.append("DltEntityId","1301164059765333889")
190
- bodyFormData.append("DltTemplateId","1307164663997173809")
191
- bodyFormData.append("SmsType","transactional")
192
-
193
- try {
194
- let config = {
195
- method: "post",
196
- maxBodyLength: Infinity,
197
- url: this.smsUrl,
198
- headers: {
199
- "Content-Type": "multipart/form-data",
200
- },
201
-
202
- data: bodyFormData,
203
- };
204
-
205
- await axios.request(config);
206
- return true;
207
-
208
- } catch (error) {
209
- console.error("Error sending sms:", error);
210
- return false;
211
- }
212
- }
213
-
214
- async sendOtpSms(obj: SmsDemoBody): Promise<boolean> {
215
- return this.sendOtpMessage(obj);
216
-
217
- }
218
-
219
- async sendWhatsAppMessage(obj: DemoBody): Promise<boolean> {
220
- if (this.testType(obj)) return this.sendMessage(obj);
221
- else return false;
222
- }
223
-
224
- async sendWhatsappTemplateMessage(
225
- obj: WhatsAppTemplateDemoBody
226
- ): Promise<boolean> {
227
- let templatevalue=await this.getTemplates();
228
- let tempVariable=obj.whatsapp.messages[0].content.template.name;
229
- let template = templatevalue.find((e:any)=>e.data.name==tempVariable)
230
- if(this.validateTemplatePayload(template,obj)){
231
- return this.sendTemplateMessage(obj)
232
- }
233
- else return false;
234
- }
235
- }
236
- export default MessageSender;
1
+ import axios from "axios";
2
+ import { DemoBody, EmiReminderAug2023, Provider, WhatsAppTemplateDemoBody } from "./Whatsapp.types";
3
+
4
+ class WhatsappMessageSender {
5
+ private exotelSid: string;
6
+ private exotelToken: string;
7
+ private exotelApiKey: string;
8
+ private whatsappApiUrl!: string;
9
+ private provider: string;
10
+
11
+ constructor(payload: {
12
+ exotelSid: string;
13
+ exotelToken: string;
14
+ exotelApiKey: string;
15
+ provider: string;
16
+ }) {
17
+ const { exotelSid, exotelToken, exotelApiKey, provider } = payload;
18
+ this.exotelSid = exotelSid;
19
+ this.exotelToken = exotelToken;
20
+ this.exotelApiKey = exotelApiKey;
21
+ this.provider = provider;
22
+
23
+ if (this.provider === Provider.EXOTEL) {
24
+ this.whatsappApiUrl = `https://${exotelApiKey}:${exotelToken}@api.exotel.com/v2/accounts/${exotelSid}/messages`;
25
+ } else if (this.provider === Provider.GUPSHUP) {
26
+ // Define the URL for Gupshup API
27
+ // this.gupshupApiUrl = ...;
28
+ }
29
+ }
30
+
31
+ async getTemplates() {
32
+ const request = await axios.get(
33
+ `https://${this.exotelApiKey}:${this.exotelToken}@api.exotel.com/v2/accounts/${this.exotelSid}/templates?waba_id=114033855070320`
34
+ );
35
+
36
+ return request.data.response.whatsapp.templates;
37
+ }
38
+ getUniquePlaceholderCount(str: string) {
39
+ const arr:Array<string> = [];
40
+ str.split("{{").map((s) => arr.push(...s.split("}}")));
41
+ const placeholders: Array<string> = arr.filter(
42
+ (i) => i.match(/[0-9]+/) && !isNaN(Number(i))
43
+ );
44
+ return [...new Set(placeholders)].length;
45
+ }
46
+
47
+ validateTemplatePayload(template:EmiReminderAug2023, payload:any) {
48
+ const templateComponents = template.data.components;
49
+ if (templateComponents.length != 2) {
50
+ return;
51
+ }
52
+
53
+ const [headerTemplate, bodyTemplate] = templateComponents;
54
+ //this checks if placeholder is correct or not
55
+ for (let index = 0; index < payload.whatsapp.messages.length; index++) {
56
+ const message = payload.whatsapp.messages[index];
57
+ const payloadComponents = message.content.template.components;
58
+ for (let index2 = 0; index2 < payloadComponents.length; index2++) {
59
+ const payloadComponent = payloadComponents[index2];
60
+ // validate template header
61
+ if (payloadComponent.type === headerTemplate.type.toLowerCase()) {
62
+ const headerPlaceholdersCount = this.getUniquePlaceholderCount(
63
+ headerTemplate.text
64
+ );
65
+ if (payloadComponent.parameters.length != headerPlaceholdersCount) {
66
+ console.log("invalid header");
67
+ throw new Error("header count mismatch");
68
+ } else {
69
+ // header validated
70
+ // TODO: add more validations if required
71
+ }
72
+ } else if (payloadComponent.type === bodyTemplate.type.toLowerCase()) {
73
+ const bodyPlaceholdersCount = this.getUniquePlaceholderCount(
74
+ bodyTemplate.text
75
+ );
76
+ if (payloadComponent.parameters.length != bodyPlaceholdersCount) {
77
+ console.log("invalid body");
78
+ throw new Error("body count mismatch");
79
+ } else {
80
+ // validate template body
81
+ // body validated
82
+ // TODO: add more validations if required
83
+ }
84
+ }
85
+ else
86
+ throw new Error("type mismatch or incorrect")
87
+
88
+ }
89
+ return true;
90
+ }
91
+ }
92
+ testType(obj: DemoBody) {
93
+ let returnValue = true;
94
+ obj.whatsapp.messages.every((message) => {
95
+ returnValue =
96
+ Boolean(message?.content?.type === "text" && message.content.text) ||
97
+ Boolean(
98
+ message?.content?.type === "document" && message.content.document
99
+ ) ||
100
+ Boolean(message?.content?.type === "image" && message.content.image) ||
101
+ Boolean(message?.content?.type === "video" && message.content.video) ||
102
+ Boolean(
103
+ message?.content?.type === "template" && message.content.template
104
+ );
105
+ return returnValue;
106
+ });
107
+ return returnValue;
108
+ }
109
+
110
+ private async sendMessage(messageData: DemoBody): Promise<boolean> {
111
+ try {
112
+ let config = {
113
+ method: "post",
114
+ maxBodyLength: Infinity,
115
+ url: this.whatsappApiUrl,
116
+ headers: {
117
+ "Content-Type": "application/json",
118
+ },
119
+
120
+ data: JSON.stringify(messageData),
121
+ };
122
+
123
+ const response = await axios.request(config);
124
+ if (response.data.metadata && response.data.metadata.success != 0) {
125
+ console.log("WhatsApp message sent successfully:", response.data);
126
+ return true;
127
+ } else {
128
+ console.error("Error sending WhatsApp message:", response.data);
129
+ return false;
130
+ }
131
+ } catch (error) {
132
+ console.error("Error sending WhatsApp message:", error);
133
+ return false;
134
+ }
135
+ }
136
+
137
+ private async sendTemplateMessage(
138
+ messageData: WhatsAppTemplateDemoBody
139
+ ): Promise<boolean> {
140
+ try {
141
+ const config = {
142
+ method: "post",
143
+ maxBodyLength: Infinity,
144
+ url: this.whatsappApiUrl,
145
+ headers: {
146
+ "Content-Type": "application/json",
147
+ },
148
+ data: JSON.stringify(messageData),
149
+ };
150
+
151
+ const response = await axios.request(config);
152
+ if (response.data.metadata && response.data.metadata.success !== 0) {
153
+ console.log(
154
+ "WhatsApp template message sent successfully:",
155
+ response.data
156
+ );
157
+ return true;
158
+ } else {
159
+ console.error(
160
+ "Error sending WhatsApp template message:",
161
+ response.data
162
+ );
163
+ return false;
164
+ }
165
+ } catch (error) {
166
+ console.error("Error sending WhatsApp template message:", error);
167
+ return false;
168
+ }
169
+ }
170
+
171
+ async sendWhatsAppMessage(obj: DemoBody): Promise<boolean> {
172
+ if (this.testType(obj)) return this.sendMessage(obj);
173
+ else return false;
174
+ }
175
+
176
+ async sendWhatsappTemplateMessage(
177
+ obj: WhatsAppTemplateDemoBody
178
+ ): Promise<boolean> {
179
+ let templatevalue=await this.getTemplates();
180
+ let tempVariable=obj.whatsapp.messages[0].content.template.name;
181
+ let template = templatevalue.find((e:any)=>e.data.name==tempVariable)
182
+ if(this.validateTemplatePayload(template,obj)){
183
+ return this.sendTemplateMessage(obj)
184
+ }
185
+ else return false;
186
+ }
187
+ }
188
+ export default WhatsappMessageSender;
package/src/index.ts CHANGED
@@ -1,8 +1,8 @@
1
- import { finance } from "./Finance";
2
- import { socials } from "./Socials";
3
-
4
-
5
- export const AeremMiddleware = {
6
- finance,socials
7
-
1
+ import { finance } from "./Finance";
2
+ import { socials } from "./Socials";
3
+
4
+
5
+ export const AeremMiddleware = {
6
+ finance,socials
7
+
8
8
  }