@meltwater/conversations-api-services 1.0.47 → 1.0.49

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.
@@ -75,30 +75,69 @@ async function privateMessage(token, _ref2, logger) {
75
75
  } = _ref2;
76
76
  let response;
77
77
  const isGif = attachment && attachment.mimeType === 'image/gif';
78
+ let payload,
79
+ isMultiPart = false;
80
+ if (attachment && attachment.mimeType.includes('image') && !isGif) {
81
+ (0, _loggerHelpers.loggerDebug)(logger, `Starting to upload image call to facebook api with recipientId ${recipientId}`, {
82
+ attachment
83
+ });
84
+ const imageResponse = await _superagent.default.get(attachment.link).responseType('arrayBuffer');
85
+ if (imageResponse.status !== 200) {
86
+ (0, _loggerHelpers.loggerError)(logger, 'Failed to fetch image from CDN', {
87
+ responseBody: JSON.stringify(imageResponse.body)
88
+ });
89
+ throw new Error('Failed to fetch image from CDN');
90
+ }
91
+ const imageBuffer = Buffer.from(imageResponse.body);
92
+ const contentType = imageResponse.headers['content-type'] || 'application/octet-stream';
93
+ const imgName = attachment.link.split('/').pop().split('?')[0];
94
+ payload = {
95
+ recipient: JSON.stringify({
96
+ id: recipientId
97
+ }),
98
+ message: JSON.stringify({
99
+ attachment: {
100
+ type: 'image',
101
+ payload: {}
102
+ }
103
+ }),
104
+ filedata: {
105
+ data: imageBuffer,
106
+ options: {
107
+ contentType,
108
+ filename: `${imgName || 'image'}.${contentType.split('/')[1]}`
109
+ }
110
+ },
111
+ tag: 'HUMAN_AGENT'
112
+ };
113
+ isMultiPart = true;
114
+ } else {
115
+ payload = {
116
+ recipient: {
117
+ id: (0, _externalIdHelpers.removePrefix)(recipientId)
118
+ },
119
+ message: {
120
+ text: text,
121
+ ...(attachment && {
122
+ attachment: {
123
+ type: isGif ? 'video' : attachment.mimeType.split('/')[0],
124
+ payload: {
125
+ url: attachment.link,
126
+ is_reusable: true
127
+ }
128
+ }
129
+ })
130
+ },
131
+ tag: 'HUMAN_AGENT'
132
+ };
133
+ }
78
134
  (0, _loggerHelpers.loggerDebug)(logger, `Starting to call facebook PM api to recipientId ${recipientId}`, {
79
135
  payload: JSON.stringify({
80
136
  text,
81
137
  attachment
82
138
  })
83
139
  });
84
- response = await postApi(`${FACEBOOK_URL}/me/messages`, token, {
85
- recipient: {
86
- id: (0, _externalIdHelpers.removePrefix)(recipientId)
87
- },
88
- message: {
89
- text: text,
90
- ...(attachment && {
91
- attachment: {
92
- type: isGif ? 'video' : attachment.mimeType.split('/')[0],
93
- payload: {
94
- url: attachment.link,
95
- is_reusable: true
96
- }
97
- }
98
- })
99
- },
100
- tag: 'HUMAN_AGENT'
101
- }, logger);
140
+ response = await postApi(`${FACEBOOK_URL}/me/messages`, token, payload, logger, isMultiPart);
102
141
  (0, _loggerHelpers.loggerInfo)(logger, `Native Facebook API Publish Private Message Response`, {
103
142
  responseBody: JSON.stringify(response.body)
104
143
  });
@@ -292,11 +331,27 @@ async function getApi(apiUrl, accessToken, payload) {
292
331
  return response;
293
332
  }
294
333
  async function postApi(apiUrl, accessToken, payload, logger) {
334
+ let isMultipart = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;
295
335
  let response = {};
296
336
  try {
297
- response = await _superagent.default.post(apiUrl).set('Accept', 'application/json').set('Content-Type', 'application/json').query({
337
+ const request = _superagent.default.post(apiUrl).set('Accept', 'application/json').query({
298
338
  access_token: accessToken
299
- }).send(payload);
339
+ });
340
+ if (isMultipart) {
341
+ request.type('form');
342
+ for (const key in payload) {
343
+ if (payload.hasOwnProperty(key)) {
344
+ if (typeof payload[key] === 'object' && payload[key].data) {
345
+ request.attach(key, payload[key].data, payload[key].options);
346
+ } else {
347
+ request.field(key, payload[key]);
348
+ }
349
+ }
350
+ }
351
+ } else {
352
+ request.set('Content-Type', 'application/json').send(payload);
353
+ }
354
+ response = await request;
300
355
  } catch (err) {
301
356
  if (err && err.response && err.response.body && err.response.body.error) {
302
357
  (0, _loggerHelpers.loggerError)(logger, `Failed to call facebook api: ${err.response.body.error.message}`);
@@ -56,30 +56,69 @@ export async function privateMessage(token, _ref2, logger) {
56
56
  } = _ref2;
57
57
  let response;
58
58
  const isGif = attachment && attachment.mimeType === 'image/gif';
59
+ let payload,
60
+ isMultiPart = false;
61
+ if (attachment && attachment.mimeType.includes('image') && !isGif) {
62
+ loggerDebug(logger, `Starting to upload image call to facebook api with recipientId ${recipientId}`, {
63
+ attachment
64
+ });
65
+ const imageResponse = await superagent.get(attachment.link).responseType('arrayBuffer');
66
+ if (imageResponse.status !== 200) {
67
+ loggerError(logger, 'Failed to fetch image from CDN', {
68
+ responseBody: JSON.stringify(imageResponse.body)
69
+ });
70
+ throw new Error('Failed to fetch image from CDN');
71
+ }
72
+ const imageBuffer = Buffer.from(imageResponse.body);
73
+ const contentType = imageResponse.headers['content-type'] || 'application/octet-stream';
74
+ const imgName = attachment.link.split('/').pop().split('?')[0];
75
+ payload = {
76
+ recipient: JSON.stringify({
77
+ id: recipientId
78
+ }),
79
+ message: JSON.stringify({
80
+ attachment: {
81
+ type: 'image',
82
+ payload: {}
83
+ }
84
+ }),
85
+ filedata: {
86
+ data: imageBuffer,
87
+ options: {
88
+ contentType,
89
+ filename: `${imgName || 'image'}.${contentType.split('/')[1]}`
90
+ }
91
+ },
92
+ tag: 'HUMAN_AGENT'
93
+ };
94
+ isMultiPart = true;
95
+ } else {
96
+ payload = {
97
+ recipient: {
98
+ id: removePrefix(recipientId)
99
+ },
100
+ message: {
101
+ text: text,
102
+ ...(attachment && {
103
+ attachment: {
104
+ type: isGif ? 'video' : attachment.mimeType.split('/')[0],
105
+ payload: {
106
+ url: attachment.link,
107
+ is_reusable: true
108
+ }
109
+ }
110
+ })
111
+ },
112
+ tag: 'HUMAN_AGENT'
113
+ };
114
+ }
59
115
  loggerDebug(logger, `Starting to call facebook PM api to recipientId ${recipientId}`, {
60
116
  payload: JSON.stringify({
61
117
  text,
62
118
  attachment
63
119
  })
64
120
  });
65
- response = await postApi(`${FACEBOOK_URL}/me/messages`, token, {
66
- recipient: {
67
- id: removePrefix(recipientId)
68
- },
69
- message: {
70
- text: text,
71
- ...(attachment && {
72
- attachment: {
73
- type: isGif ? 'video' : attachment.mimeType.split('/')[0],
74
- payload: {
75
- url: attachment.link,
76
- is_reusable: true
77
- }
78
- }
79
- })
80
- },
81
- tag: 'HUMAN_AGENT'
82
- }, logger);
121
+ response = await postApi(`${FACEBOOK_URL}/me/messages`, token, payload, logger, isMultiPart);
83
122
  loggerInfo(logger, `Native Facebook API Publish Private Message Response`, {
84
123
  responseBody: JSON.stringify(response.body)
85
124
  });
@@ -273,11 +312,27 @@ async function getApi(apiUrl, accessToken, payload) {
273
312
  return response;
274
313
  }
275
314
  async function postApi(apiUrl, accessToken, payload, logger) {
315
+ let isMultipart = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;
276
316
  let response = {};
277
317
  try {
278
- response = await superagent.post(apiUrl).set('Accept', 'application/json').set('Content-Type', 'application/json').query({
318
+ const request = superagent.post(apiUrl).set('Accept', 'application/json').query({
279
319
  access_token: accessToken
280
- }).send(payload);
320
+ });
321
+ if (isMultipart) {
322
+ request.type('form');
323
+ for (const key in payload) {
324
+ if (payload.hasOwnProperty(key)) {
325
+ if (typeof payload[key] === 'object' && payload[key].data) {
326
+ request.attach(key, payload[key].data, payload[key].options);
327
+ } else {
328
+ request.field(key, payload[key]);
329
+ }
330
+ }
331
+ }
332
+ } else {
333
+ request.set('Content-Type', 'application/json').send(payload);
334
+ }
335
+ response = await request;
281
336
  } catch (err) {
282
337
  if (err && err.response && err.response.body && err.response.body.error) {
283
338
  loggerError(logger, `Failed to call facebook api: ${err.response.body.error.message}`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@meltwater/conversations-api-services",
3
- "version": "1.0.47",
3
+ "version": "1.0.49",
4
4
  "description": "Repository to contain all conversations api services shared across our services",
5
5
  "main": "dist/cjs/data-access/index.js",
6
6
  "module": "dist/esm/data-access/index.js",
@@ -1,29 +1,30 @@
1
1
  import superagent from 'superagent';
2
2
  import { removePrefix } from '../../lib/externalId.helpers.js';
3
- import { loggerDebug, loggerError, loggerInfo } from '../../lib/logger.helpers.js';
3
+ import {
4
+ loggerDebug,
5
+ loggerError,
6
+ loggerInfo,
7
+ } from '../../lib/logger.helpers.js';
4
8
 
5
9
  const FACEBOOK_URL = 'https://graph.facebook.com';
6
10
 
7
-
8
11
  export async function shareCount(token, externalId, logger) {
9
- try{
12
+ try {
10
13
  const response = await getApi(
11
- `${FACEBOOK_URL}/${removePrefix(
12
- externalId
13
- )}/?fields=shares`,
14
+ `${FACEBOOK_URL}/${removePrefix(externalId)}/?fields=shares`,
14
15
  token
15
16
  );
16
17
  return response.body.shares && response.body.shares.count;
17
- }catch(err){
18
- loggerError(logger,
18
+ } catch (err) {
19
+ loggerError(
20
+ logger,
19
21
  `Facebook shareCount error recieved - ${error.code}`,
20
- error,
22
+ error
21
23
  );
22
24
  }
23
25
  }
24
26
 
25
27
  export async function reactions(token, externalIds, logger) {
26
-
27
28
  try {
28
29
  const response = await getApi(
29
30
  `${FACEBOOK_URL}?ids=${externalIds
@@ -40,7 +41,8 @@ export async function reactions(token, externalIds, logger) {
40
41
  );
41
42
  return response.body;
42
43
  } catch (error) {
43
- loggerError(logger,
44
+ loggerError(
45
+ logger,
44
46
  `Facebook reactions error recieved - ${error.code}`,
45
47
  error
46
48
  );
@@ -48,15 +50,16 @@ export async function reactions(token, externalIds, logger) {
48
50
  }
49
51
  }
50
52
 
51
- export async function comment(token, {
52
- inReplyToExternalId,
53
- text,
54
- attachment = undefined,
55
- }, logger = undefined) {
53
+ export async function comment(
54
+ token,
55
+ { inReplyToExternalId, text, attachment = undefined },
56
+ logger = undefined
57
+ ) {
56
58
  let response;
57
59
  const isGif = attachment && attachment.mimeType === 'image/gif';
58
60
 
59
- loggerDebug(logger,
61
+ loggerDebug(
62
+ logger,
60
63
  `Starting to call facebook comment api inReplyToExternalId ${inReplyToExternalId}`,
61
64
  { text, attachment }
62
65
  );
@@ -66,37 +69,74 @@ export async function comment(token, {
66
69
  token,
67
70
  {
68
71
  ...(text && text.length && { message: text }),
69
- ...(attachment &&
70
- !isGif && { attachment_url: attachment.link }),
72
+ ...(attachment && !isGif && { attachment_url: attachment.link }),
71
73
  ...(attachment &&
72
74
  isGif && { attachment_share_url: attachment.link }),
73
75
  },
74
76
  logger
75
77
  );
76
- loggerInfo(logger,
78
+ loggerInfo(
79
+ logger,
77
80
  `Native Facebook API Publish Comment Response to externalId ${inReplyToExternalId}`,
78
81
  { responseBody: JSON.stringify(response.body) }
79
82
  );
80
83
  return response.body;
81
84
  }
82
85
 
83
- export async function privateMessage(token, {
84
- recipientId,
85
- text,
86
- attachment = undefined,
87
- }, logger){
86
+ export async function privateMessage(
87
+ token,
88
+ { recipientId, text, attachment = undefined },
89
+ logger
90
+ ) {
88
91
  let response;
89
92
  const isGif = attachment && attachment.mimeType === 'image/gif';
90
93
 
91
- loggerDebug(logger,
92
- `Starting to call facebook PM api to recipientId ${recipientId}`,
93
- { payload: JSON.stringify({text, attachment}) }
94
- );
94
+ let payload,
95
+ isMultiPart = false;
95
96
 
96
- response = await postApi(
97
- `${FACEBOOK_URL}/me/messages`,
98
- token,
99
- {
97
+ if (attachment && attachment.mimeType.includes('image') && !isGif) {
98
+ loggerDebug(
99
+ logger,
100
+ `Starting to upload image call to facebook api with recipientId ${recipientId}`,
101
+ { attachment }
102
+ );
103
+
104
+ const imageResponse = await superagent
105
+ .get(attachment.link)
106
+ .responseType('arrayBuffer');
107
+
108
+ if (imageResponse.status !== 200) {
109
+ loggerError(logger, 'Failed to fetch image from CDN', {
110
+ responseBody: JSON.stringify(imageResponse.body),
111
+ });
112
+ throw new Error('Failed to fetch image from CDN');
113
+ }
114
+
115
+ const imageBuffer = Buffer.from(imageResponse.body);
116
+ const contentType =
117
+ imageResponse.headers['content-type'] || 'application/octet-stream';
118
+
119
+ const imgName = attachment.link.split('/').pop().split('?')[0];
120
+
121
+ payload = {
122
+ recipient: JSON.stringify({ id: recipientId }),
123
+ message: JSON.stringify({
124
+ attachment: { type: 'image', payload: {} },
125
+ }),
126
+ filedata: {
127
+ data: imageBuffer,
128
+ options: {
129
+ contentType,
130
+ filename: `${imgName || 'image'}.${
131
+ contentType.split('/')[1]
132
+ }`,
133
+ },
134
+ },
135
+ tag: 'HUMAN_AGENT',
136
+ };
137
+ isMultiPart = true;
138
+ } else {
139
+ payload = {
100
140
  recipient: { id: removePrefix(recipientId) },
101
141
  message: {
102
142
  text: text,
@@ -113,20 +153,32 @@ export async function privateMessage(token, {
113
153
  }),
114
154
  },
115
155
  tag: 'HUMAN_AGENT',
116
- },
117
- logger
156
+ };
157
+ }
158
+
159
+ loggerDebug(
160
+ logger,
161
+ `Starting to call facebook PM api to recipientId ${recipientId}`,
162
+ { payload: JSON.stringify({ text, attachment }) }
118
163
  );
119
- loggerInfo(logger,
120
- `Native Facebook API Publish Private Message Response`,
121
- { responseBody: JSON.stringify(response.body) }
164
+
165
+ response = await postApi(
166
+ `${FACEBOOK_URL}/me/messages`,
167
+ token,
168
+ payload,
169
+ logger,
170
+ isMultiPart
122
171
  );
172
+
173
+ loggerInfo(logger, `Native Facebook API Publish Private Message Response`, {
174
+ responseBody: JSON.stringify(response.body),
175
+ });
176
+
123
177
  return response.body;
124
178
  }
125
179
 
126
180
  export async function hide(token, externalId, logger) {
127
- loggerDebug(logger,
128
- `Starting to call facebook hide api`
129
- );
181
+ loggerDebug(logger, `Starting to call facebook hide api`);
130
182
 
131
183
  const response = await postApi(
132
184
  `${FACEBOOK_URL}/${removePrefix(externalId)}`,
@@ -135,17 +187,14 @@ export async function hide(token, externalId, logger) {
135
187
  logger
136
188
  );
137
189
 
138
- loggerInfo(logger
139
- `Native Facebook API Hide Response`,
140
- { responseBody: JSON.stringify(response.body) }
141
- );
190
+ loggerInfo(logger`Native Facebook API Hide Response`, {
191
+ responseBody: JSON.stringify(response.body),
192
+ });
142
193
  return response.body;
143
194
  }
144
195
 
145
196
  export async function unhide(token, externalId, logger) {
146
- loggerDebug(logger,
147
- `Starting to call facebook unhide api`
148
- );
197
+ loggerDebug(logger, `Starting to call facebook unhide api`);
149
198
 
150
199
  const response = await postApi(
151
200
  `${FACEBOOK_URL}/${removePrefix(externalId)}`,
@@ -154,18 +203,14 @@ export async function unhide(token, externalId, logger) {
154
203
  logger
155
204
  );
156
205
 
157
- loggerInfo(
158
- `Native Facebook API Unhide Response`,
159
- { responseBody: JSON.stringify(response.body) }
160
- );
206
+ loggerInfo(`Native Facebook API Unhide Response`, {
207
+ responseBody: JSON.stringify(response.body),
208
+ });
161
209
  return response.body;
162
210
  }
163
211
 
164
212
  export async function like(token, externalId, logger) {
165
-
166
- loggerDebug(logger,
167
- `Starting to call facebook like api`
168
- );
213
+ loggerDebug(logger, `Starting to call facebook like api`);
169
214
 
170
215
  const response = await postApi(
171
216
  `${FACEBOOK_URL}/${removePrefix(externalId)}/likes`,
@@ -174,18 +219,14 @@ export async function like(token, externalId, logger) {
174
219
  logger
175
220
  );
176
221
 
177
- loggerInfo(logger,
178
- `Native Facebook API Like Response`,
179
- { responseBody: JSON.stringify(response.body) }
180
- );
222
+ loggerInfo(logger, `Native Facebook API Like Response`, {
223
+ responseBody: JSON.stringify(response.body),
224
+ });
181
225
  return response.body;
182
226
  }
183
227
 
184
228
  export async function unlike(token, externalId, logger) {
185
-
186
- loggerDebug(logger,
187
- `Starting to call facebook unlike api`
188
- );
229
+ loggerDebug(logger, `Starting to call facebook unlike api`);
189
230
 
190
231
  const response = await deleteApi(
191
232
  `${FACEBOOK_URL}/${removePrefix(externalId)}/likes`,
@@ -194,10 +235,9 @@ export async function unlike(token, externalId, logger) {
194
235
  logger
195
236
  );
196
237
 
197
- loggerInfo( logger,
198
- `Native Facebook API Unlike Response`,
199
- { responseBody: JSON.stringify(response.body) }
200
- );
238
+ loggerInfo(logger, `Native Facebook API Unlike Response`, {
239
+ responseBody: JSON.stringify(response.body),
240
+ });
201
241
  return response.body;
202
242
  }
203
243
 
@@ -231,7 +271,8 @@ export async function isUserBanned(token, authorId, pageId, logger) {
231
271
  }
232
272
  }
233
273
 
234
- loggerInfo( logger,
274
+ loggerInfo(
275
+ logger,
235
276
  `Native Facebook API is User Banned Response was invalid`,
236
277
  {
237
278
  responseBody: JSON.stringify(response.body),
@@ -256,14 +297,14 @@ export async function getProfile(token, authorId, logger) {
256
297
  .query({ access_token: token })
257
298
  .send();
258
299
  } catch (err) {
259
- if (
260
- err?.response?.body?.error
261
- ) {
262
- loggerError(logger,
300
+ if (err?.response?.body?.error) {
301
+ loggerError(
302
+ logger,
263
303
  `Failed to call facebook api for userId ${userNoPrefix}: ${err.response.body.error.message}`
264
304
  );
265
305
  } else {
266
- loggerError(logger,
306
+ loggerError(
307
+ logger,
267
308
  `Failed to call facebook api for userId ${userNoPrefix}`,
268
309
  err
269
310
  );
@@ -273,7 +314,8 @@ export async function getProfile(token, authorId, logger) {
273
314
  }
274
315
 
275
316
  if (response.status !== 200) {
276
- loggerError(logger,
317
+ loggerError(
318
+ logger,
277
319
  `Failed to call facebook api for userId ${userNoPrefix}`,
278
320
  { responseBody: JSON.stringify(response.body) }
279
321
  );
@@ -288,7 +330,8 @@ export async function getProfile(token, authorId, logger) {
288
330
  }
289
331
 
290
332
  export async function ban(token, sourceId, authorId, logger) {
291
- loggerDebug( logger,
333
+ loggerDebug(
334
+ logger,
292
335
  `Starting to call facebook ban api for externalAuthorId ${authorId} ${sourceId}`
293
336
  );
294
337
 
@@ -299,7 +342,8 @@ export async function ban(token, sourceId, authorId, logger) {
299
342
  logger
300
343
  );
301
344
 
302
- loggerInfo(logger,
345
+ loggerInfo(
346
+ logger,
303
347
  `Native Facebook API Hide Response for externalAuthorId ${authorId}`,
304
348
  { responseBody: JSON.stringify(response.body) }
305
349
  );
@@ -307,8 +351,8 @@ export async function ban(token, sourceId, authorId, logger) {
307
351
  }
308
352
 
309
353
  export async function unban(token, sourceId, authorId, logger) {
310
-
311
- loggerDebug( logger,
354
+ loggerDebug(
355
+ logger,
312
356
  `Starting to call facebook unban api for externalAuthorId ${authorId} ${sourceId}`
313
357
  );
314
358
 
@@ -319,7 +363,8 @@ export async function unban(token, sourceId, authorId, logger) {
319
363
  logger
320
364
  );
321
365
 
322
- loggerInfo( logger,
366
+ loggerInfo(
367
+ logger,
323
368
  `Native Facebook API Unban Response for externalAuthorId ${authorId}`,
324
369
  { responseBody: JSON.stringify(response.body) }
325
370
  );
@@ -329,7 +374,7 @@ export async function unban(token, sourceId, authorId, logger) {
329
374
  export async function getAttachment(token, externalId, discussionType, logger) {
330
375
  let result;
331
376
  try {
332
- switch(discussionType) {
377
+ switch (discussionType) {
333
378
  case 're':
334
379
  case 'qt':
335
380
  result = await getApi(
@@ -341,7 +386,7 @@ export async function getAttachment(token, externalId, discussionType, logger) {
341
386
  undefined,
342
387
  logger
343
388
  );
344
-
389
+
345
390
  return {
346
391
  images: [
347
392
  {
@@ -356,10 +401,12 @@ export async function getAttachment(token, externalId, discussionType, logger) {
356
401
  `${FACEBOOK_URL}/${removePrefix(
357
402
  externalId
358
403
  )}?fields=attachments`,
359
- token,undefined,undefined,
404
+ token,
405
+ undefined,
406
+ undefined,
360
407
  logger
361
408
  );
362
-
409
+
363
410
  return {
364
411
  images: result?.body?.attachments?.data.map((item) => {
365
412
  return {
@@ -372,10 +419,12 @@ export async function getAttachment(token, externalId, discussionType, logger) {
372
419
  `${FACEBOOK_URL}/${removePrefix(
373
420
  externalId
374
421
  )}/attachments?fields=media,subattachments,file_url`,
375
- token, undefined, undefined,
422
+ token,
423
+ undefined,
424
+ undefined,
376
425
  logger
377
426
  );
378
-
427
+
379
428
  // if subattachments exist, use them
380
429
  const res = result?.body?.data[0];
381
430
  if (res?.subattachments) {
@@ -383,28 +432,29 @@ export async function getAttachment(token, externalId, discussionType, logger) {
383
432
  images: res?.subattachments.data.map((item) => {
384
433
  return {
385
434
  source:
386
- item?.media?.source || item?.media?.image?.src,
435
+ item?.media?.source ||
436
+ item?.media?.image?.src,
387
437
  };
388
438
  }),
389
439
  };
390
440
  }
391
-
441
+
392
442
  return {
393
443
  images: [
394
444
  {
395
- source: res?.media?.source || res?.media?.image?.src,
445
+ source:
446
+ res?.media?.source || res?.media?.image?.src,
396
447
  },
397
448
  ],
398
449
  };
399
450
  }
400
451
  } catch (error) {
401
- loggerError(logger,`Error getting facebook attachment`, error);
452
+ loggerError(logger, `Error getting facebook attachment`, error);
402
453
  throw error;
403
454
  }
404
455
  }
405
456
 
406
457
  async function getApi(apiUrl, accessToken, payload, queryParams = {}, logger) {
407
-
408
458
  let response = {};
409
459
  try {
410
460
  response = await superagent
@@ -420,11 +470,13 @@ async function getApi(apiUrl, accessToken, payload, queryParams = {}, logger) {
420
470
  err.response.body &&
421
471
  err.response.body.error
422
472
  ) {
423
- loggerError(logger,
473
+ loggerError(
474
+ logger,
424
475
  `Failed to call facebook getApi ${apiUrl}: ${err.response.body.error.message}`
425
476
  );
426
477
  } else {
427
- loggerError(logger,
478
+ loggerError(
479
+ logger,
428
480
  `Failed to call facebook getApi ${apiUrl}`,
429
481
  err
430
482
  );
@@ -434,13 +486,10 @@ async function getApi(apiUrl, accessToken, payload, queryParams = {}, logger) {
434
486
  }
435
487
 
436
488
  if (response.status !== 200) {
437
- loggerError(logger,
438
- `Failed to call facebook api ${apiUrl}`,
439
- { responseBody: JSON.stringify(response.body) }
440
- );
441
- let error = new Error(
442
- `Failed to call facebook api ${apiUrl}`
443
- );
489
+ loggerError(logger, `Failed to call facebook api ${apiUrl}`, {
490
+ responseBody: JSON.stringify(response.body),
491
+ });
492
+ let error = new Error(`Failed to call facebook api ${apiUrl}`);
444
493
  error.code = response.status;
445
494
  throw error;
446
495
  }
@@ -448,16 +497,40 @@ async function getApi(apiUrl, accessToken, payload, queryParams = {}, logger) {
448
497
  return response;
449
498
  }
450
499
 
451
- async function postApi(apiUrl, accessToken, payload, logger) {
452
-
500
+ async function postApi(
501
+ apiUrl,
502
+ accessToken,
503
+ payload,
504
+ logger,
505
+ isMultipart = false
506
+ ) {
453
507
  let response = {};
454
508
  try {
455
- response = await superagent
509
+ const request = superagent
456
510
  .post(apiUrl)
457
511
  .set('Accept', 'application/json')
458
- .set('Content-Type', 'application/json')
459
- .query({ access_token: accessToken })
460
- .send(payload);
512
+ .query({ access_token: accessToken });
513
+
514
+ if (isMultipart) {
515
+ request.type('form');
516
+ for (const key in payload) {
517
+ if (payload.hasOwnProperty(key)) {
518
+ if (typeof payload[key] === 'object' && payload[key].data) {
519
+ request.attach(
520
+ key,
521
+ payload[key].data,
522
+ payload[key].options
523
+ );
524
+ } else {
525
+ request.field(key, payload[key]);
526
+ }
527
+ }
528
+ }
529
+ } else {
530
+ request.set('Content-Type', 'application/json').send(payload);
531
+ }
532
+
533
+ response = await request;
461
534
  } catch (err) {
462
535
  if (
463
536
  err &&
@@ -465,36 +538,30 @@ async function postApi(apiUrl, accessToken, payload, logger) {
465
538
  err.response.body &&
466
539
  err.response.body.error
467
540
  ) {
468
- loggerError(logger,
541
+ loggerError(
542
+ logger,
469
543
  `Failed to call facebook api: ${err.response.body.error.message}`
470
544
  );
471
545
  } else {
472
- loggerError(logger,
473
- `Failed to call facebook api`,
474
- err
475
- );
546
+ loggerError(logger, `Failed to call facebook api`, err);
476
547
  }
477
- if(response.status){
548
+ if (response.status) {
478
549
  throw new Error(response.statusText);
479
550
  }
480
551
  throw err;
481
552
  }
482
553
 
483
554
  if (response.status !== 200) {
484
- loggerError(logger,
485
- `Failed to call facebook api`,
486
- { responseBody: JSON.stringify(response.body) }
487
- );
488
- throw new Error(
489
- `Failed to call facebook api ${response.body}`
490
- );
555
+ loggerError(logger, `Failed to call facebook api`, {
556
+ responseBody: JSON.stringify(response.body),
557
+ });
558
+ throw new Error(`Failed to call facebook api ${response.body}`);
491
559
  }
492
560
 
493
561
  return response;
494
562
  }
495
563
 
496
564
  async function deleteApi(apiUrl, accessToken, payload, logger) {
497
-
498
565
  let response = {};
499
566
  try {
500
567
  response = await superagent
@@ -510,30 +577,25 @@ async function deleteApi(apiUrl, accessToken, payload, logger) {
510
577
  err.response.body &&
511
578
  err.response.body.error
512
579
  ) {
513
- loggerError(logger,
580
+ loggerError(
581
+ logger,
514
582
  `Failed to call facebook api delete: ${err.response.body.error.message}`
515
583
  );
516
584
  } else {
517
- loggerError(logger,
518
- `Failed to call facebook api delete`,
519
- err
520
- );
585
+ loggerError(logger, `Failed to call facebook api delete`, err);
521
586
  }
522
587
 
523
588
  throw err;
524
589
  }
525
590
 
526
591
  if (response.status !== 200) {
527
- loggerError(logger,
528
- `Failed to call facebook api delete`,
529
- { responseBody: JSON.stringify(response.body) }
530
- );
531
- let error = new Error(
532
- `Failed to call facebook api delete`
533
- );
592
+ loggerError(logger, `Failed to call facebook api delete`, {
593
+ responseBody: JSON.stringify(response.body),
594
+ });
595
+ let error = new Error(`Failed to call facebook api delete`);
534
596
  error.code = response.status;
535
597
  throw error;
536
598
  }
537
599
 
538
600
  return response;
539
- }
601
+ }