@meltwater/conversations-api-services 1.0.47 → 1.0.48

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