-
Notifications
You must be signed in to change notification settings - Fork 41
/
bynder-js-sdk.js
1026 lines (949 loc) · 38.3 KB
/
bynder-js-sdk.js
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
require("isomorphic-form-data");
const axios = require("axios");
const { basename } = require("path");
const isUrl = require("is-url");
const joinUrl = require("proper-url-join");
const queryString = require("query-string");
const simpleOAuth2 = require("simple-oauth2");
const pkg = require("../package.json");
const url = require("url");
const defaultAssetsNumberPerPage = 50;
/**
* Rejects the request.
* @return {Promise} error - Returns a Promise with the details for the wrong request.
*/
function rejectValidation(module, param) {
return Promise.reject({
status: 0,
message: `The ${module} ${param} is not valid or it was not specified properly`
});
}
/**
* @classdesc Represents an API call.
* @class
* @abstract
*/
class APICall {
/**
* Create a APICall.
* @constructor
* @param {string} baseURL - A string with the base URL for account.
* @param {string} httpsAgent - A https agent.
* @param {string} httpAgent - A http agent.
* @param {string} token - Optional OAuth2 access token
* @param {Object} [data={}] - An object containing the query parameters.
*/
constructor(baseURL, httpsAgent, httpAgent, token) {
if (!isUrl(baseURL)) throw new Error("The base URL provided is not valid");
this.baseURL = baseURL;
this.httpsAgent = httpsAgent;
this.httpAgent = httpAgent;
this.token = token;
}
/**
* Fetch the information from the API.
* @return {Promise} - Returns a Promise that, when fulfilled, will either return an JSON Object with the requested
* data or an Error with the problem.
*/
async send(method, url, data = {}) {
let callURL = joinUrl(this.baseURL, url, { trailingSlash: true });
if (!this.token && !this.permanentToken) {
throw new Error("No token found");
}
const headers = {
'User-Agent': "bynder-js-sdk/" + pkg.version
};
if (this.permanentToken) {
headers["Authorization"] = "Bearer " + this.permanentToken;
} else {
this.token = await (this.token.expired()
? this.token.refresh()
: Promise.resolve(this.token));
headers["Authorization"] = "Bearer " + this.token.token.access_token;
}
let body = "";
if (method === "POST") {
headers["Content-Type"] = "application/x-www-form-urlencoded";
body = queryString.stringify(data);
} else if (Object.keys(data).length && data.constructor === Object) {
callURL = joinUrl(callURL, { trailingSlash: true, query: data });
}
return axios(callURL, {
httpsAgent: this.httpsAgent,
httpAgent: this.httpAgent,
method,
data: body,
headers
}).then(response => {
if (response.status >= 400) {
// check for 4XX, 5XX, wtv
return Promise.reject({
status: response.status,
message: response.statusText,
body: response.data
});
}
if (response.status >= 200 && response.status <= 202) {
return response.data;
}
return {};
});
}
}
const bodyTypes = {
BUFFER: "BUFFER",
BLOB: "BLOB",
STREAM: "STREAM",
/**
* @param {Object} body - The file body whose type we need to determine
* @return {string} One of bodyTypes.BUFFER, bodyTypes.BLOB, bodyTypes.STREAM
*/
get: body => {
if (typeof Buffer !== "undefined" && Buffer.isBuffer(body)) {
return bodyTypes.BUFFER;
}
if (
typeof window !== "undefined" &&
window.Blob &&
body instanceof window.Blob
) {
return bodyTypes.BLOB;
}
if (typeof body.read === "function") {
return bodyTypes.STREAM;
}
return null;
}
};
/**
* @return {number} length - The amount of data that can be read from the file
*/
function getLength(file) {
const { body, length } = file;
const bodyType = bodyTypes.get(body);
if (bodyType === bodyTypes.BUFFER) {
return body.length;
}
if (bodyType === bodyTypes.BLOB) {
return body.size;
}
return length;
}
/**
* @classdesc Represents the Bynder SDK. It allows the user to make every call to the API with a single function.
* @class
*/
class Bynder {
/**
* Create Bynder SDK.
* @constructor
* @param {String} options.baseURL - The URL with the account domain.
* @param {String} options.httpsAgent - The https agent.
* @param {String} options.httpAgent - The http agent.
* @param {String} options.clientId -- OAuth2 client id
* @param {String} options.clientSecret -- OAuth2 client secret
* @param
* @param {Object} options - An object containing the consumer keys, access keys and the base URL.
*/
constructor(options) {
this.options = options;
this.baseURL = options.baseURL;
this.redirectUri = options.redirectUri;
this.api = new APICall(
options.baseURL,
options.httpsAgent,
options.httpAgent
);
if (typeof options.permanentToken === "string") {
this.api.permanentToken = options.permanentToken;
return;
}
const oauthBaseUrl = url.resolve(options.baseURL, "/v6/authentication/");
this.oauth2 = simpleOAuth2.create({
client: {
id: options.clientId,
secret: options.clientSecret
},
auth: {
tokenHost: oauthBaseUrl,
tokenPath: "oauth2/token",
revokePath: "oauth2/revoke",
authorizeHost: oauthBaseUrl,
authorizePath: "oauth2/auth"
}
});
if (options.token) {
if (typeof options.token.access_token !== "string") {
throw new Error(
"Invalid token format: " + JSON.stringify(options.token, null, 2)
);
}
this.api.token = this.oauth2.accessToken.create(options.token);
}
}
/**
* Builds OAuth2 authorization URL.
* @return {String} Authorization URL
*/
makeAuthorizationURL(state, scope) {
return this.oauth2.authorizationCode.authorizeURL({
redirect_uri: this.redirectUri,
scope: scope,
state: state
});
}
/**
* Gets OAuth2 access token from authorization code
* @param {String} code - One time authorization code
* @return {String} access token
*/
getToken(code) {
const tokenConfig = {
code: code,
redirect_uri: this.redirectUri
};
return this.oauth2.authorizationCode.getToken(tokenConfig).then(result => {
const token = this.oauth2.accessToken.create(result);
this.api.token = token;
return token;
});
}
/**
* Get all the smartfilters.
* @see {@link https://bynder.docs.apiary.io/#reference/smartfilters/smartfilters-operations/retrieve-smartfilters|API Call}
* @return {Promise} Smartfilters - Returns a Promise that, when fulfilled, will either return an Array with the
* smartfilters or an Error with the problem.
*/
getSmartfilters() {
return this.api.send("GET", "v4/smartfilters/");
}
/**
* Login to retrieve OAuth credentials.
* @see {@link https://bynder.docs.apiary.io/#reference/users/-deprecated-login-a-user-operations/login-a-user|API Call}
* @param {Object} params={} - An object containing the credentials with which the user intends to login.
* @param {String} params.username - The username of the user.
* @param {String} params.password - The password of the user.
* @param {String} params.consumerId - The consumerId of the user.
* @return {Promise} Credentials - Returns a Promise that, when fulfilled, will either return an Object with the
* OAuth credentials for login or an Error with the problem.
*/
userLogin(params) {
if (!params.username || !params.password || !params.consumerId) {
return rejectValidation(
"authentication",
"username, password or consumerId"
);
}
return this.api.send("POST", "v4/users/login/", params);
}
/**
* Get the assets according to the parameters provided.
* @see {@link http://docs.bynder.apiary.io/#reference/assets/asset-operations/retrieve-assets|API Call}
* @param {Object} [params={}] - An object containing the parameters accepted by the API to narrow the query.
* @return {Promise} Assets - Returns a Promise that, when fulfilled, will either return an Array with the assets or
* an Error with the problem.
*/
getMediaList(params = {}) {
return this.api.send("GET", "v4/media/", {
...params,
count: false,
...(Array.isArray(params.propertyOptionId)
? params.propertyOptionId.join(",")
: {})
});
}
/**
* Get the assets information according to the id provided.
* @see {@link http://docs.bynder.apiary.io/#reference/assets/specific-asset-operations/retrieve-specific-asset|API Call}
* @param {Object} params - An object containing the id and the version of the desired asset.
* @param {String} params.id - The id of the desired asset.
* @param {Boolean} [params.versions] - Whether to include info about the different asset versions.
* @return {Promise} Asset - Returns a Promise that, when fulfilled, will either return an Object with the asset or
* an Error with the problem.
*/
getMediaInfo({ id, ...options } = {}) {
if (!id) {
return rejectValidation("media", "id");
}
return this.api.send("GET", `v4/media/${id}/`, options);
}
/**
* Get all the assets starting from the page provided (1 by default) and incrementing according to the offset given.
* @see {@link http://docs.bynder.apiary.io/#reference/assets/asset-operations/retrieve-assets|API Call}
* @param {Object} [params={}] - An object containing the parameters accepted by the API to narrow the query.
* @return {Promise} Assets - Returns a Promise that, when fulfilled, will either return an Array with all the
* assets or an Error with the problem.
*/
getAllMediaItems(params = {}) {
const recursiveGetAssets = (_params, assets) => {
let queryAssets = assets;
const params = { ..._params };
params.page = !params.page ? 1 : params.page;
params.limit = !params.limit ? defaultAssetsNumberPerPage : params.limit;
return this.getMediaList(params)
.then(data => {
queryAssets = assets.concat(data);
if (data && data.length === params.limit) {
// If the results page is full it means another one might exist
params.page += 1;
return recursiveGetAssets(params, queryAssets);
}
return queryAssets;
})
.catch(error => {
return error;
});
};
return recursiveGetAssets(params, []);
}
/**
* Get the assets total according to the parameters provided.
* @see {@link http://docs.bynder.apiary.io/#reference/assets/asset-operations/retrieve-assets|API Call}
* @param {Object} [params={}] - An object containing the parameters accepted by the API to narrow the query.
* @return {Promise} Number - Returns a Promise that, when fulfilled, will either return the number of assets
* fitting the query or an Error with the problem.
*/
getMediaTotal(params = {}) {
const parametersObject = Object.assign({}, params, { count: true });
if (Array.isArray(parametersObject.propertyOptionId)) {
parametersObject.propertyOptionId = parametersObject.propertyOptionId.join();
}
return this.api.send("GET", "v4/media/", parametersObject).then(data => {
return data.count.total;
});
}
/**
* Edit an existing asset with the information provided.
* @see {@link http://docs.bynder.apiary.io/#reference/assets/specific-asset-operations/modify-asset|API Call}
* @param {Object} params={} - An object containing the parameters accepted by the API to change in the asset.
* @param {String} params.id - The id of the desired asset.
* @return {Promise} Object - Returns a Promise that, when fulfilled, will either return an empty Object in
* case it's successful or an Error with the problem.
*/
editMedia(params = {}) {
if (!params.id) {
return rejectValidation("media", "id");
}
return this.api.send("POST", "v4/media/", params);
}
/**
* Delete an existing asset.
* @see {@link http://docs.bynder.apiary.io/#reference/assets/specific-asset-operations/delete-asset|API Call}
* @param {Object} params={} - An object containing the id of the asset to be deleted.
* @param {String} params.id - The id of the asset.
* @return {Promise} Object - Returns a Promise that, when fulfilled, will either return an empty Object in
* case it's successful or an Error with the problem.
*/
deleteMedia({ id }) {
if (!id) {
return rejectValidation("media", "id");
}
return this.api.send("DELETE", `v4/media/${id}/`);
}
/**
* Get all the metaproperties
* @see {@link http://docs.bynder.apiary.io/#reference/metaproperties/retrieve-metaproperties|API Call}
* @param {Object} params={} - An object containing the parameters accepted by the API to narrow the query.
* @return {Promise} Metaproperties - Returns a Promise that, when fulfilled, will either return an Array with the
* metaproperties or an Error with the problem.
*/
getMetaproperties(params = {}) {
return this.api.send("GET", "v4/metaproperties/", params).then(data => {
return Object.keys(data).map(metaproperty => {
return data[metaproperty];
});
});
}
/**
* Get the metaproperty information according to the id provided.
* @see {@link http://docs.bynder.apiary.io/#reference/metaproperties/specific-metaproperty-operations/retrieve-specific-metaproperty|API Call}
* @param {Object} params={} - An object containing the id of the desired metaproperty.
* @param {String} params.id - The id of the desired metaproperty.
* @return {Promise} Metaproperty - Returns a Promise that, when fulfilled, will either return an Object with the
* metaproperty or an Error with the problem.
*/
getMetaproperty({ id } = {}) {
if (!id) {
return rejectValidation("metaproperty", "id");
}
return this.api.send("GET", `v4/metaproperties/${id}/`);
}
/**
* Save a new metaproperty in the information provided.
* @see {@link http://docs.bynder.apiary.io/#reference/metaproperties/metaproperty-operations/create-metaproperty|API Call}
* @param {Object} object={} - An object containing the data of the new metaproperty.
* @return {Promise} Object - Returns a Promise that, when fulfilled, will either return an empty Object in
* case it's successful or an Error with the problem.
*/
saveNewMetaproperty(params = {}) {
return this.api.send("POST", "v4/metaproperties/", {
data: JSON.stringify(params)
});
// The API requires an object with the query content stringified inside
}
/**
* Modify new metaproperty with the information provided.
* @see {@link https://bynder.docs.apiary.io/#reference/metaproperties/specific-metaproperty-operations/modify-metaproperty|API Call}
* @param {Object} object={} - An object containing the data of the metaproperty.
* @param {String} params.id - The id of the desired metaproperty.
* @return {Promise} Object - Returns a Promise that, when fulfilled, will either return an empty Object in
* case it's successful or an Error with the problem.
*/
editMetaproperty({ id, ...params } = {}) {
if (!id) {
return rejectValidation("metaproperty", "id");
}
return this.api.send("POST", `v4/metaproperties/${id}/`, {
data: JSON.stringify(params)
});
// The API requires an object with the query content stringified inside
}
/**
* Delete the metaproperty with the provided id.
* @see {@link http://docs.bynder.apiary.io/#reference/metaproperties/delete-metaproperty|API Call}
* @param {Object} object={} - An object containing the id of the metaproperty to be deleted.
* @param {String} object.id - The id of the metaproperty.
* @return {Promise} Object - Returns a Promise that, when fulfilled, will either return an empty Object in
* case it's successful or an Error with the problem.
*/
deleteMetaproperty({ id } = {}) {
if (!id) {
return rejectValidation("metaproperty", "id");
}
return this.api.send("DELETE", `v4/metaproperties/${id}/`);
}
/**
* Add an option of metaproperty
* @see {@link http://docs.bynder.apiary.io/#reference/metaproperties/specific-metaproperty-operations/create-metaproperty-option|API Call}
* @param {Object} params={} - An object containing the id of the desired metaproperty.
* @param {String} params.id - The id of the desired metaproperty.
* @param {String} params.name - The name of the desired metaproperty.
* @return {Promise} Response - Returns a Promise that, when fulfilled, will either return an Object with the
* response or an Error with the problem.
*/
saveNewMetapropertyOption({ id, ...params } = {}) {
if (!id || !params.name) {
return rejectValidation("metaproperty option", "id or name");
}
return this.api.send("POST", `v4/metaproperties/${id}/options/`, {
data: JSON.stringify(params)
});
}
/**
* modify an option of metaproperty
* @see {@link http://docs.bynder.apiary.io/#reference/metaproperties/specific-metaproperty-operations/modify-metaproperty-option|API Call}
* @param {Object} params={} - An object containing the id of the desired metaproperty.
* @param {String} params.id - The id of the desired metaproperty.
* @param {String} params.optionId - The id of the desired option.
* @param {String} params.name - The id of the desired metaproperty.
* @return {Promise} Response - Returns a Promise that, when fulfilled, will either return an Object with the
* response or an Error with the problem.
*/
editMetapropertyOption({ id, ...params } = {}) {
if (!id || !params.optionId) {
return rejectValidation("metaproperty option", "id or optionId");
}
return this.api.send(
"POST",
`v4/metaproperties/${id}/options/${params.optionId}/`,
{ data: JSON.stringify(params) }
);
}
/**
* delete an option of metaproperty
* @see {@link http://docs.bynder.apiary.io/#reference/metaproperties/specific-metaproperty-operations/delete-metaproperty-option|API Call}
* @param {Object} params={} - An object containing the id of the desired metaproperty.
* @param {String} params.id - The id of the desired metaproperty.
* @param {String} params.optionId - The id of the desired option.
* @param {String} params.name - The id of the desired metaproperty.
* @return {Promise} Response - Returns a Promise that, when fulfilled, will either return an Object with the
* response or an Error with the problem.
*/
deleteMetapropertyOption({ id, optionId }) {
if (!id || !optionId) {
return rejectValidation("metaproperty option", "id or optionId");
}
return this.api.send(
"DELETE",
`v4/metaproperties/${id}/options/${optionId}/`
);
}
/**
* Get the assets usage information according to the id provided.
* @see {@link https://bynder.docs.apiary.io/#reference/asset-usage/asset-usage-operations/retrieve-asset-usage|API Call}
* @param {Object} queryObject - An object containing the id of the desired asset.
* @param {String} queryObject.id - The id of the desired asset to retrieve usage for.
* @return {Promise} Asset Usage - Returns a Promise that, when fulfilled, will either return an Object with
* the asset usage or an Error with the problem.
*/
getAssetUsage(queryObject) {
if (!queryObject.id) {
return rejectValidation("asset usage", "id");
}
const request = new APICall(
this.baseURL,
"media/usage/",
"GET",
this.consumerToken,
this.accessToken,
{ asset_id: queryObject.id }
);
return request.send();
}
/**
* Create a usage for an asset according to the provided query object.
* @see {@link https://bynder.docs.apiary.io/#reference/asset-usage/asset-usage-operations/create-asset-usage|API Call}
* @param {Object} queryObject - An object containing the properties for the desired asset usage.
* @param {String} queryObject.id - The id of the desired asset to create a usage for.
* @param {String} queryObject.integration_id - The id of the desired integration to add.
* @param {String} queryObject.timestamp - Datetime. ISO8601 format: yyyy-mm-ddThh:mm:ssZ.
* @param {String} queryObject.uri - Location. Example: /hippo/first_post.
* @param {String} queryObject.additional - Additional information. Example: Usage description.
* @return {Promise} Asset usage - Returns a Promise that, when fulfilled, will either return an Object with
* the asset usage or an Error with the problem.
*/
saveNewAssetUsage(queryObject) {
if (!queryObject.id) {
return rejectValidation("asset usage", "id");
}
if (!queryObject.integration_id) {
return rejectValidation("asset usage", "integration_id");
}
const request = new APICall(
this.baseURL,
"media/usage/",
"POST",
this.consumerToken,
this.accessToken,
{
asset_id: queryObject.id,
integration_id: queryObject.integration_id,
timestamp: queryObject.timestamp || null,
uri: queryObject.uri || null,
additional: queryObject.additional || null
}
);
return request.send();
}
/**
* Deletes an asset usage based on the provided asset and integration ids.
* @see {@link https://bynder.docs.apiary.io/#reference/asset-usage/asset-usage-operations/delete-asset-usage|API Call}
* @param {Object} queryObject - An object containing the id of the desired asset.
* @param {String} queryObject.id - The id of the desired asset to retrieve usage for.
* @param {String} queryObject.integration_id - The id of the desired integration to delete.
* @param {String} queryObject.uri - Location. Example: /hippo/first_post.
* @return {Promise} Asset Usage - Returns a Promise that, when fulfilled, will either return an Object with
* the asset usage or an Error with the problem.
*/
deleteAssetUsage(queryObject) {
if (!queryObject.id) {
return rejectValidation("asset usage", "id");
}
if (!queryObject.integration_id) {
return rejectValidation("asset usage", "integration_id");
}
const request = new APICall(
this.baseURL,
"media/usage/",
"DELETE",
this.consumerToken,
this.accessToken,
{
asset_id: queryObject.id,
integration_id: queryObject.integration_id,
uri: queryObject.uri || null
}
);
return request.send();
}
/**
* Get all the tags
* @see {@link http://docs.bynder.apiary.io/#reference/tags/tags-access/retrieve-entry-point|API Call}
* @param {Object} [params={}] - An object containing the parameters accepted by the API to narrow the query.
* @return {Promise} Tags - Returns a Promise that, when fulfilled, will either return an Array with the
* tags or an Error with the problem.
*/
getTags(params = {}) {
return this.api.send("GET", "v4/tags/", params);
}
/**
* Get collections according to the parameters provided
* @see {@link http://docs.bynder.apiary.io/#reference/collections/collection-operations/retrieve-collections|API Call}
* @param {Object} [params={}] - An object containing the parameters accepted by the API to narrow the query.
* @return {Promise} Collections - Returns a Promise that, when fulfilled, will either return an Array with the
* collections or an Error with the problem.
*/
getCollections(params = {}) {
return this.api.send("GET", "v4/collections/", params);
}
/**
* Get the collection information according to the id provided.
* @see {@link http://docs.bynder.apiary.io/#reference/collections/specific-collection-operations/retrieve-specific-collection|API Call}
* @param {Object} params={} - An object containing the id of the desired collection.
* @param {String} params.id - The id of the desired collection.
* @return {Promise} Collection - Returns a Promise that, when fulfilled, will either return an Object with the
* collection or an Error with the problem.
*/
getCollection({ id } = {}) {
if (!id) {
return rejectValidation("collection", "id");
}
return this.api.send("GET", `v4/collections/${id}/`);
}
/**
* Create the collection information according to the name provided.
* @see {@link http://docs.bynder.apiary.io/#reference/collections/specific-collection-operations/create-collection|API Call}
* @param {Object} params={} - An object containing the id of the desired collection.
* @param {String} params.name - The name of the desired collection.
* @param {String} params.description - The description of the desired collection.
* @return {Promise} Response - Returns a Promise that, when fulfilled, will either return an Object with the
* response or an Error with the problem.
*/
saveNewCollection(params = {}) {
if (!params.name) {
return rejectValidation("collection", "name");
}
return this.api.send("POST", "v4/collections/", params);
}
/**
* Add assets to the desired collection.
* @see {@link http://docs.bynder.apiary.io/#reference/collections/specific-collection-operations/add-asset-to-a-collection|API Call}
* @param {Object} params={} - An object containing the id of the desired collection.
* @param {String} params.id - The id of the shared collection.
* @param {String} params.data - JSON-serialised list of asset ids to add.
* @return {Promise} Response - Returns a Promise that, when fulfilled, will either return an Object with the
* response or an Error with the problem.
*/
addMediaToCollection({ id, data } = {}) {
if (!id) {
return rejectValidation("collection", "id");
}
if (!data) {
return rejectValidation("collection", "data");
}
return this.api.send("POST", `v4/collections/${id}/media/`, {
data: JSON.stringify(data)
});
}
/**
* Remove assets from desired collection.
* @see {@link http://docs.bynder.apiary.io/#reference/collections/specific-collection-operations/remove-asset-from-a-collection|API Call}
* @param {Object} params={} - An object containing the id of the desired collection and deleteIds of assets.
* @param {String} params.id - The id of the shared collection.
* @param {String} params.deleteIds - Asset ids to remove from the collection
* @return {Promise} Response - Returns a Promise that, when fulfilled, will either return an Object with the
* response or an Error with the problem.
*/
deleteMediaFromCollection({ id, deleteIds } = {}) {
if (!id) {
return rejectValidation("collection", "id");
}
if (!deleteIds) {
return rejectValidation("collection", "deleteIds");
}
return this.api.send("DELETE", `v4/collections/${id}/media/`, {
deleteIds: Array.isArray(deleteIds) ? deleteIds.join(",") : deleteIds
});
}
/**
* Share the collection to the recipients provided.
* @see {@link http://docs.bynder.apiary.io/#reference/collections/specific-collection-operations/share-collection|API Call}
* @param {Object} params={} - An object containing the id of the desired collection.
* @param {String} params.id - The id of the shared collection.
* @param {String} params.recipients - The email addressed of the recipients.
* @param {String} params.collectionOptions - The recipent right of the shared collection: view, edit
* @return {Promise} Collection - Returns a Promise that, when fulfilled, will either return an Object with the
* collection or an Error with the problem.
*/
shareCollection({ id, ...params } = {}) {
if (!id) {
return rejectValidation("collection", "id");
}
if (!params.recipients) {
return rejectValidation("collection", "recipients");
}
if (!params.collectionOptions) {
return rejectValidation("collection", "collectionOptions");
}
return this.api.send("POST", `v4/collections/${id}/share/`, params);
}
/**
* Get a list of brands and subbrands
* @see {@link https://bynder.docs.apiary.io/#reference/security-roles/specific-security-profile/retrieve-brands-and-subbrands}
* @return {Promise}
*/
getBrands() {
return this.api.send("GET", "v4/brands/");
}
/**
* Gets the closest Amazon S3 bucket location to upload to.
* @see {@link https://bynder.docs.apiary.io/#reference/upload-assets/1-get-closest-amazons3-upload-endpoint/get-closest-amazons3-upload-endpoint}
* @return {Promise} Amazon S3 location url string.
*/
getClosestUploadEndpoint() {
return this.api.send("GET", "upload/endpoint");
}
/**
* Starts the upload process. Registers a file upload with Bynder and returns authorisation information to allow
* uploading to the Amazon S3 bucket-endpoint.
* @see {@link https://bynder.docs.apiary.io/#reference/upload-assets/2-initialise-upload/initialise-upload}
* @param {String} filename - filename
* @return {Promise} Relevant S3 file information, necessary for the file upload.
*/
initUpload(filename) {
if (!filename) {
return rejectValidation("upload", "filename");
}
return this.api.send("POST", "upload/init", { filename });
}
/**
* Registers a temporary chunk in Bynder.
* @see {@link https://bynder.docs.apiary.io/#reference/upload-assets/3-upload-file-in-chunks-and-register-every-uploaded-chunk/register-uploaded-chunk}
* @param {Object} init - result from init upload
* @param {Number} chunkNumber - chunk number
* @return {Promise}
*/
registerChunk(init, chunkNumber) {
const { s3file, s3_filename: filename } = init;
const { uploadid, targetid } = s3file;
return this.api.send("POST", "v4/upload/", {
id: uploadid,
targetid,
filename: `${filename}/p${chunkNumber}`,
chunkNumber
});
}
/**
* Finalises the file upload when all chunks finished uploading and registers it in Bynder.
* @see {@link https://bynder.docs.apiary.io/#reference/upload-assets/4-finalise-a-completely-uploaded-file/finalise-a-completely-uploaded-file}
* @param {Object} init - Result from init upload
* @param {String} fileName - Original file name
* @param {Number} chunks - Number of chunks
* @param {String} [mediaId] - Media ID of the asset the file will be added to as additional
* @return {Promise}
*/
finaliseUpload(init, filename, chunks, mediaId) {
const { s3file, s3_filename: s3filename } = init;
const { uploadid, targetid } = s3file;
const payload = {
targetid,
s3_filename: `${s3filename}/p${chunks}`,
chunks
}
if (mediaId) {
const finalizeUrl = `v4/media/${mediaId}/save/additional/${uploadid}`;
return this.api.send("POST", finalizeUrl, payload);
} else {
return this.api.send("POST", `v4/upload/${uploadid}/`, {...payload, original_filename: filename});
}
}
/**
* Checks if the files have finished uploading.
* @see {@link https://bynder.docs.apiary.io/#reference/upload-assets/5-poll-processing-state-of-finalised-files/retrieve-entry-point}
* @param {String[]} importIds - The import IDs of the files to be checked.
* @return {Promise}
*/
pollUploadStatus(importIds) {
return this.api.send("GET", "v4/upload/poll/", {
items: importIds.join(",")
});
}
/**
* Resolves once assets are uploaded, or rejects after 60 attempts with 2000ms between them
* @param {String[]} importIds - The import IDs of the files to be checked.
* @return {Promise}
*/
waitForUploadDone(importIds) {
const POLLING_INTERVAL = 2000;
const MAX_POLLING_ATTEMPTS = typeof process === 'object'
? process.env.BYNDER_MAX_POLLING_ATTEMPTS || 60
: 60;
const pollUploadStatus = this.pollUploadStatus.bind(this);
return new Promise((resolve, reject) => {
let attempt = 0;
(function checkStatus() {
pollUploadStatus(importIds)
.then(pollStatus => {
if (pollStatus !== null) {
const { itemsDone, itemsFailed } = pollStatus;
if (itemsDone.length === importIds.length) {
// done !
return resolve({ itemsDone });
}
if (itemsFailed.length > 0) {
// failed
return reject({ itemsFailed });
}
}
if (++attempt > MAX_POLLING_ATTEMPTS) {
// timed out
return reject(
new Error(`Stopped polling after ${attempt} attempts`)
);
}
return setTimeout(checkStatus, POLLING_INTERVAL);
})
.catch(reject);
})();
});
}
/**
* Saves a media asset in Bynder. If media id is specified in the data a new version of the asset will be saved.
* Otherwise a new asset will be saved.
* @see {@link https://bynder.docs.apiary.io/#reference/upload-assets/4-finalise-a-completely-uploaded-file/save-as-a-new-asset}
* @param {Object} data - Asset data
* @return {Promise}
*/
saveAsset(data) {
const { brandId, mediaId } = data;
if (!brandId) {
return rejectValidation("upload", "brandId");
}
const saveURL = mediaId ? `v4/media/${mediaId}/save/` : "v4/media/save/";
return this.api.send("POST", saveURL, data);
}
/**
* Uploads arbirtrarily sized buffer or stream file to provided S3 endpoint in chunks and registers each chunk to Bynder.
* Resolves the passed init result and final chunk number.
* @param {Object} file ={} - An object containing the id of the desired collection.
* @param {String} file.filename - The file name of the file to be saved
* @param {Buffer|Readable} file.body - The file to be uploaded. Can be either buffer or a read stream.
* @param {Number} file.length - The length of the file to be uploaded
* @param {string} endpoint - S3 endpoint url
* @param {Object} init - Result from init upload
* @return {Promise}
*/
uploadFileInChunks(file, endpoint, init) {
const { body } = file;
const bodyType = bodyTypes.get(body);
const length = getLength(file);
const CHUNK_SIZE = 1024 * 1024 * 5;
const chunks = Math.ceil(length / CHUNK_SIZE);
const registerChunk = this.registerChunk.bind(this);
const uploadPath = init.multipart_params.key;
const uploadChunkToS3 = (chunkData, chunkNumber) => {
const form = new FormData();
const params = Object.assign(init.multipart_params, {
name: `${basename(uploadPath)}/p${chunkNumber}`,
chunk: chunkNumber,
chunks,
Filename: `${uploadPath}/p${chunkNumber}`,
key: `${uploadPath}/p${chunkNumber}`
});
Object.keys(params).forEach(key => {
form.append(key, params[key]);
});
form.append("file", chunkData);
let opts;
if (typeof window !== "undefined") {
opts = {}; // With browser based FormData headers are taken care of automatically
} else {
opts = {
headers: Object.assign(form.getHeaders(), {
"content-length": form.getLengthSync()
})
};
}
return axios.post(endpoint, form, opts);
};
function delay(ms) {
return new Promise(resolve => {
setTimeout(resolve, ms);
});
}
// sequentially upload chunks to AWS, then register them
function nextChunk(chunkNumber) {
if (chunkNumber >= chunks) {
return Promise.resolve({ init, chunkNumber });
}
let chunkData;
if (bodyType === bodyTypes.STREAM) {
// handle stream data
chunkData = body.read(CHUNK_SIZE);
if (chunkData === null) {
// our read stream is not done yet reading
// let's wait for a while...
return delay(50).then(() => {
return nextChunk(chunkNumber);
});
}
} else {
// handle buffer/blob data
const start = chunkNumber * CHUNK_SIZE;
const end = Math.min(start + CHUNK_SIZE, length);
chunkData = body.slice(start, end);
}
const newChunkNumber = chunkNumber + 1;
return uploadChunkToS3(chunkData, newChunkNumber)
.then(() => {
return registerChunk(init, newChunkNumber);
})
.then(() => {
return nextChunk(newChunkNumber);
});
}
return nextChunk(0);
}
/**
* Uploads an arbitrarily sized buffer or stream file and returns the uploaded asset information
* @see {@link https://bynder.docs.apiary.io/#reference/upload-assets}
* @param {Object} file={} - An object containing the id of the desired collection.
* @param {String} file.filename - The file name of the file to be saved
* @param {Buffer|Readable} file.body - The file to be uploaded. Can be either buffer or a read stream.
* @param {Number} file.length - The length of the file to be uploaded
* @param {Object} file.data={} - An object containing the assets' attributes
* @param {Boolean} file.additional - Boolean that signals if the asset should be added as additional to an existing asset
* @return {Promise} The information of the uploaded file, including IDs and all final file urls.
*/
uploadFile(file) {
const { body, filename, data, additional } = file;
const { brandId } = data;
const bodyType = bodyTypes.get(body);
const length = getLength(file);
if (!brandId) {
return rejectValidation("upload", "brandId");
}
if (!filename) {
return rejectValidation("upload", "filename");
}
if (!body || !bodyType) {
return rejectValidation("upload", "body");
}
if (!length || typeof length !== "number") {
return rejectValidation("upload", "length");
}
if (additional && !data.id) {
return rejectValidation("upload", "id");
}
const getClosestUploadEndpoint = this.getClosestUploadEndpoint.bind(this);
const initUpload = this.initUpload.bind(this);
const uploadFileInChunks = this.uploadFileInChunks.bind(this);
const finaliseUpload = this.finaliseUpload.bind(this);
const saveAsset = this.saveAsset.bind(this);
const waitForUploadDone = this.waitForUploadDone.bind(this);
return Promise.all([getClosestUploadEndpoint(), initUpload(filename)])