forked from contentstack/contentstack-javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontentstack.js
More file actions
2746 lines (2363 loc) · 95 KB
/
contentstack.js
File metadata and controls
2746 lines (2363 loc) · 95 KB
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
module.exports =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // identity function for calling harmony imports with the correct context
/******/ __webpack_require__.i = function(value) { return value; };
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 12);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(process) {
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof2 = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
exports.transform = transform;
exports._type = _type;
exports.mergeDeep = mergeDeep;
exports.merge = merge;
exports.isBrowser = isBrowser;
exports.parseQueryFromParams = parseQueryFromParams;
exports.getHash = getHash;
exports.generateHash = generateHash;
exports.resultWrapper = resultWrapper;
exports.spreadResult = spreadResult;
exports.sendRequest = sendRequest;
var _request = __webpack_require__(2);
var _request2 = _interopRequireDefault(_request);
var _result = __webpack_require__(14);
var _result2 = _interopRequireDefault(_result);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* @method addSpread
* @description method to add the spread.
*/
(function addSpread() {
if (Promise.prototype.spread) return;
Promise.prototype.spread = function (fn, errFunc) {
errFunc = errFunc || function (err) {};
return this.then(function (args) {
return fn.apply(fn, args);
}).catch(function (err) {
errFunc(err);
});
};
})();
function transform(type) {
return function () {
this._query[type] = this._query[type] || {};
switch (arguments.length) {
case 1:
if (Array.isArray(arguments[0]) || typeof arguments[0] === "string") {
var query = this._query[type]['BASE'] || [];
query = query.concat(arguments[0]);
this._query[type]['BASE'] = query;
return this;
} else {
console.error("Kindly provide valid parameters");
}
break;
case 2:
if (typeof arguments[0] === "string" && (Array.isArray(arguments[1]) || typeof arguments[1] === "string")) {
var _query2 = this._query[type][arguments[0]] || [];
_query2 = _query2.concat(arguments[1]);
this._query[type][arguments[0]] = _query2;
return this;
} else {
console.error("Kindly provide valid parameters");
}
break;
default:
console.error("Kindly provide valid parameters");
}
};
}
function _type(val) {
var _typeof = void 0,
__typeof = typeof val === 'undefined' ? 'undefined' : _typeof2(val);
switch (__typeof) {
case 'object':
_typeof = __typeof;
if (Array.isArray(val)) {
__typeof = 'array';
}
break;
default:
_typeof = __typeof;
}
return __typeof;
};
// merge two objects
function mergeDeep(target, source) {
var self = this;
var _merge_recursive = function _merge_recursive(target, source) {
for (var key in source) {
if (self._type(source[key]) == 'object' && self._type(target[key]) == self._type(source[key])) {
_merge_recursive(target[key], source[key]);
} else if (self._type(source[key]) == 'array' && self._type(target[key]) == self._type(source[key])) {
target[key] = target[key].concat(source[key]);
} else {
target[key] = source[key];
}
}
};
_merge_recursive(target, source);
return target;
};
// merge two objects
function merge(target, source) {
if (target && source) {
for (var key in source) {
target[key] = source[key];
}
}
return target;
};
// return true if process is running in browser else false
function isBrowser() {
return typeof window !== "undefined" && (typeof process === 'undefined' ? 'undefined' : _typeof2(process)) === "object" && process.title === "browser";
};
// return the query from the params
function parseQueryFromParams(queryObject, single, toJSON) {
if (queryObject && queryObject.requestParams) {
var _query = merge({}, queryObject.requestParams.body ? queryObject.requestParams.body.query || {} : {});
if (_query.environment_uid) {
delete _query.environment_uid;
_query.environment = queryObject.environment;
}
_query.environment = queryObject.environment;
return {
content_type_uid: queryObject.content_type_uid,
locale: _query.locale || 'en-us',
query: _query,
entry_uid: queryObject.entry_uid,
asset_uid: queryObject.asset_uid,
single: single || "false",
toJSON: toJSON || "false",
api_key: queryObject.requestParams.headers ? queryObject.requestParams.headers.api_key : ""
};
}
};
// returrn the hash value of the query
function getHash(query) {
try {
var hashValue = generateHash(JSON.stringify(query)),
keyArray = [];
keyArray.push(query.content_type_uid);
keyArray.push(query.locale);
if (query.entry_uid) keyArray.push(query.entry_uid);
if (query.asset_uid) keyArray.push(query.asset_uid);
keyArray.push(hashValue);
return keyArray.join('.');
} catch (e) {}
};
// return the hash value of the string
function generateHash(str) {
var hash = 0,
i = void 0,
chr = void 0,
len = void 0;
if (str.length === 0) return hash;
for (i = 0, len = str.length; i < len; i++) {
chr = str.charCodeAt(i);
hash = (hash << 5) - hash + chr;
hash |= 0; // Convert to 32bit integer
}
return hash < -1 ? hash * -1 : hash;
};
// generate the Result object
function resultWrapper(result) {
if (result && typeof result.entries !== 'undefined') {
if (result.entries && result.entries.length) {
for (var i = 0, _i = result.entries.length; i < _i; i++) {
result.entries[i] = (0, _result2.default)(result.entries[i]);
}
} else {
result.entries = [];
}
} else if (result && result.assets && typeof result.assets !== 'undefined') {
if (result.assets && result.assets.length) {
for (var j = 0, _j = result.assets.length; j < _j; j++) {
result.assets[j] = (0, _result2.default)(result.assets[j]);
}
} else {
result.assets = [];
}
} else if (result && typeof result.entry !== 'undefined') {
result.entry = (0, _result2.default)(result.entry);
} else if (result && typeof result.asset !== 'undefined') {
result.asset = (0, _result2.default)(result.asset);
} else if (result && typeof result.items !== 'undefined') {
result.items = (0, _result2.default)(result.items).toJSON();
}
return result;
};
// spread the result object
function spreadResult(result) {
var _results = [];
if (result && Object.keys(result).length) {
if (typeof result.entries !== 'undefined') _results.push(result.entries);
if (typeof result.assets !== 'undefined') _results.push(result.assets);
if (typeof result.content_type !== 'undefined' || typeof result.schema !== 'undefined') _results.push(result.content_type || result.schema);
if (typeof result.count !== 'undefined') _results.push(result.count);
if (typeof result.entry !== 'undefined') _results = result.entry;
if (typeof result.asset !== 'undefined') _results = result.asset;
if (typeof result.items !== 'undefined') _results.push(result);
}
return _results;
};
function sendRequest(queryObject) {
var env_uid = queryObject.environment_uid;
if (env_uid) {
queryObject._query.environment_uid = env_uid;
} else {
if (queryObject._query) {
queryObject._query.environment = queryObject.environment;
} else {
queryObject['_query'] = {};
queryObject._query['environment'] = queryObject.environment;
}
}
var self = queryObject;
var continueFlag = false;
var cachePolicy = typeof self.queryCachePolicy !== 'undefined' ? self.queryCachePolicy : self.cachePolicy;
var tojson = typeof self.tojson !== 'undefined' ? self.tojson : false;
var isSingle = self.entry_uid || self.singleEntry || self.asset_uid ? true : false;
var hashQuery = getHash(parseQueryFromParams(self, isSingle, tojson));
/**
for new api v3
*/
if (queryObject && queryObject.requestParams && queryObject.requestParams.body && queryObject.requestParams.body.query) {
var cloneQueryObj = JSON.parse(JSON.stringify(queryObject.requestParams.body.query));
if ((typeof cloneQueryObj === 'undefined' ? 'undefined' : _typeof2(cloneQueryObj)) !== 'object') {
cloneQueryObj = JSON.parse(cloneQueryObj);
}
delete queryObject.requestParams.body.query;
queryObject.requestParams.body = merge(queryObject.requestParams.body, cloneQueryObj);
}
var getCacheCallback = function getCacheCallback() {
return function (err, entries) {
return new Promise(function (resolve, reject) {
try {
if (err) throw err;
if (!tojson) entries = resultWrapper(entries);
resolve(spreadResult(entries));
} catch (e) {
reject(e);
}
});
};
};
var callback = function callback(continueFlag, resolve, reject) {
if (continueFlag) {
(0, _request2.default)(queryObject.requestParams).then(function (data) {
try {
self.entry_uid = self.asset_uid = self.tojson = self.queryCachePolicy = undefined;
var entries = {};
var syncstack = {};
if (queryObject.singleEntry) {
queryObject.singleEntry = false;
if (data.schema) entries.schema = data.schema;
if (data.content_type) {
entries.content_type = data.content_type;
delete entries.schema;
}
if (data.entries && data.entries.length) {
entries.entry = data.entries[0];
} else if (data.assets && data.assets.length) {
entries.assets = data.assets[0];
} else {
if (cachePolicy === 2) {
self.provider.get(hashQuery, getCacheCallback());
} else {
return reject({ error_code: 141, error_message: 'The requested entry doesn\'t exist.' });
}
return;
}
} else if (data.items) {
syncstack = {
items: data.items,
pagination_token: data.pagination_token,
sync_token: data.sync_token,
total_count: data.total_count
};
} else {
entries = data;
}
if (cachePolicy !== -1) {
self.provider.set(hashQuery, entries, function (err) {
try {
if (err) throw err;
if (!tojson) entries = resultWrapper(entries);
return resolve(spreadResult(entries));
} catch (e) {
return reject(e);
}
});
return resolve(spreadResult(entries));
}
if (Object.keys(syncstack).length) {
return resolve(syncstack);
}
if (!tojson) entries = resultWrapper(entries);
return resolve(spreadResult(entries));
} catch (e) {
return reject({
message: e.message
});
}
}.bind(self)).catch(function (error) {
if (cachePolicy === 2) {
self.provider.get(hashQuery, getCacheCallback());
} else {
return reject(error);
}
});
}
};
switch (cachePolicy) {
case 1:
return new Promise(function (resolve, reject) {
self.provider.get(hashQuery, function (err, _data) {
try {
if (err || !_data) {
callback(true, resolve, reject);
} else {
if (!tojson) _data = resultWrapper(_data);
return resolve(spreadResult(_data));
}
} catch (e) {
return reject(e);
}
});
});
break;
case 2:
case 0:
case undefined:
case -1:
return new Promise(function (resolve, reject) {
callback(true, resolve, reject);
});
};
if (cachePolicy === 3) {
return {
cache: function () {
return new Promise(function (resolve, reject) {
self.provider.get(hashQuery, function (err, _data) {
try {
if (err) {
reject(err);
} else {
if (!tojson) _data = resultWrapper(_data);
resolve(spreadResult(_data));
}
} catch (e) {
reject(e);
}
});
});
}(),
network: function () {
return new Promise(function (resolve, reject) {
callback(true, resolve, reject);
});
}(),
both: function both(_callback_) {
self.provider.get(hashQuery, function (err, entries) {
if (!tojson) entries = resultWrapper(entries);
_callback_(err, spreadResult(entries));
});
(0, _request2.default)(queryObject.requestParams).then(function (data) {
try {
self.entry_uid = self.tojson = self.queryCachePolicy = undefined;
var entries = {},
error = null;
if (queryObject.singleEntry) {
queryObject.singleEntry = false;
if (data.schema) entries.schema = data.schema;
if (data.content_type) {
entries.content_type = data.content_type;
delete entries.schema;
}
if (data.entries && data.entries.length) {
entries.entry = data.entries[0];
} else if (data.assets && data.assets.length) {
entries.assets = data.assets[0];
} else {
error = { error_code: 141, error_message: 'The requested entry doesn\'t exist.' };
}
} else {
entries = data;
}
if (!tojson) entries = resultWrapper(entries);
_callback_(error, spreadResult(entries));
} catch (e) {
_callback_(e);
}
}.bind(self)).catch(function (error) {
_callback_(error);
});
}
};
}
};
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9)))
/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
/*import Sync from './modules/sync';*/
var _config = __webpack_require__(7);
var _config2 = _interopRequireDefault(_config);
var _utils = __webpack_require__(0);
var Utils = _interopRequireWildcard(_utils);
var _entry = __webpack_require__(5);
var _entry2 = _interopRequireDefault(_entry);
var _assets = __webpack_require__(13);
var _assets2 = _interopRequireDefault(_assets);
var _query = __webpack_require__(6);
var _query2 = _interopRequireDefault(_query);
var _request = __webpack_require__(2);
var _request2 = _interopRequireDefault(_request);
var _cache = __webpack_require__(4);
var cache = _interopRequireWildcard(_cache);
var _index = __webpack_require__(3);
var _index2 = _interopRequireDefault(_index);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* Expose `Stack`.
* @ignore
*/
var Stack = function () {
function Stack() {
_classCallCheck(this, Stack);
this.config = _config2.default;
this.cachePolicy = _index2.default.policies.IGNORE_CACHE;
this.provider = _index2.default.providers('localstorage');
//this.sync_cdn_api_key = stack_arguments[0].sync_cdn_api_key;
for (var _len = arguments.length, stack_arguments = Array(_len), _key = 0; _key < _len; _key++) {
stack_arguments[_key] = arguments[_key];
}
switch (stack_arguments.length) {
case 1:
if (_typeof(stack_arguments[0]) === "object" && typeof stack_arguments[0].api_key === "string" && typeof stack_arguments[0].access_token === "string" && typeof stack_arguments[0].environment === "string") {
this.headers = {
api_key: stack_arguments[0].api_key,
access_token: stack_arguments[0].access_token
};
this.environment = stack_arguments[0].environment;
return this;
} else {
console.error("Kindly provide valid object parameters.");
}
case 3:
if (typeof stack_arguments[0] === "string" && typeof stack_arguments[1] === "string" && typeof stack_arguments[2] === "string") {
this.headers = {
api_key: stack_arguments[0],
access_token: stack_arguments[1]
};
this.environment = stack_arguments[2];
return this;
} else {
console.error("Kindly provide valid string parameters.");
}
default:
console.error("Kindly provide valid parameters to initialize the Built.io Contentstack javascript-SDK Stack.");
}
}
/**
* @method setPort
* @description Sets the port of the host.
* @param {Number} port - Port Number
* @return Stack
* */
_createClass(Stack, [{
key: 'setPort',
value: function setPort(port) {
if (typeof port === "number") this.config.port = port;
return this;
}
/**
* @method setProtocol
* @description Sets the protocol of the host.
* @param {String} protocol - http/https protocol
* @return Stack
* */
}, {
key: 'setProtocol',
value: function setProtocol(protocol) {
if (typeof protocol === "string" && ~["https", "http"].indexOf(protocol)) this.config.protocol = protocol;
return this;
}
/**
* @method setHost
* @description Sets the host of the API server.
* @param {String} host - valid ip or host
* @return Stack
* */
}, {
key: 'setHost',
value: function setHost(host) {
if (typeof host === "string" && host) this.config.host = host;
return this;
}
/**
* @method setCachePolicy
* @description setCachePolicy which contains different cache policies.
* @param {Constant} [key=ONLY_NETWORK] - Cache policy to be applied on Stack or Query.
* @example
* Stack.setCachePolicy(Contentstack.CachePolicy.IGNORE_CACHE)
* Stack.setCachePolicy(Contentstack.CachePolicy.ONLY_NETWORK)
* Stack.setCachePolicy(Contentstack.CachePolicy.CACHE_ELSE_NETWORK)
* Stack.setCachePolicy(Contentstack.CachePolicy.NETWORK_ELSE_CACHE)
* Stack.setCachePolicy(Contentstack.CachePolicy.CACHE_THEN_NETWORK)
* @returns {Stack}
*/
}, {
key: 'setCachePolicy',
value: function setCachePolicy(policy) {
if (typeof policy === 'number' && policy >= -1 && policy < 4) {
if (!this._query) {
this.cachePolicy = policy;
} else {
this.queryCachePolicy = policy;
}
} else {
console.error("Kindly provide the valid policy");
}
return this;
}
/**
* @method setCacheProvider
* @description Set 'Cache Provider' object.
* @example
* Stack
* .setCacheProvider({
* get: function (key, callback) {
* // custom logic
* },
* set: function (key, value, callback) {
* // custom logic
* }
* });
* @returns {Stack}
*/
}, {
key: 'setCacheProvider',
value: function setCacheProvider(provider) {
if (provider && (typeof provider === 'undefined' ? 'undefined' : _typeof(provider)) === 'object') {
this.provider = provider;
}
return this;
}
/**
* @method clearByQuery
* @description 'clearByQuery' function to clear the query from the cache.
* @example
* Stack.clearQuery(query, callback);
* @ignore
*/
}, {
key: 'clearByQuery',
value: function clearByQuery() {
if (this.provider && typeof this.provider.clearByQuery === 'function') {
return this.provider.clearByQuery.apply(this.provider, arguments);
}
}
/**
* @method clearByContentType
* @description 'clearByContentType' function to clear the query from the cache by specified content type.
* @example
* Stack.clearByContentType(content_type_uid, callback);
* Stack.clearByContentType(content_type_uid, language_uid, callback);
* @ignore
*/
}, {
key: 'clearByContentType',
value: function clearByContentType() {
if (this.provider && typeof this.provider.clearByContentType === 'function') {
return this.provider.clearByContentType.apply(this.provider, arguments);
}
}
/**
* @method clearAll
* @description 'clearAll' function to clear all the queries from cache.
* @example
* Stack.clearAll(callback);
* @ignore
*/
}, {
key: 'clearAll',
value: function clearAll() {
if (this.provider && typeof this.provider.clearAll === 'function') {
return this.provider.clearAll.apply(this.provider, arguments);
}
}
/**
* @method getCacheProvider
* @description Returns currently set CacheProvider object.
* @example Stack.getCacheProvider();
* @returns {Object}
*/
}, {
key: 'getCacheProvider',
value: function getCacheProvider() {
return this.provider;
}
/**
* @method ContentType
* @description Set "ContentType" from the Stack from where you want to retrive the entries.
* @param {String} [content_type_uid] - uid of the existing contenttype
* @returns {Stack}
*/
}, {
key: 'ContentType',
value: function ContentType(uid) {
if (uid && typeof uid === 'string') {
this.content_type_uid = uid;
this.type = "contentType";
}
return this;
}
/**
* @method Entry
* @description Set the Entry Uid which you want to retrive from the Contenttype specified.
* @param {String} uid - entry_uid
* @example ContentType('blog').Entry('blt1234567890abcef')
* @returns {Entry}
*/
}, {
key: 'Entry',
value: function Entry(uid) {
var entry = new _entry2.default();
if (uid && typeof uid === "string") {
entry.entry_uid = uid;
}
return Utils.merge(entry, this);
}
/**
* @method Assets
* @description Set the Asset Uid which you want to retrive the Asset.
* @param {String} uid - asset_uid
* @example Stack.Assets('blt1234567890abcef').fetch
* @returns {Assets}
*/
}, {
key: 'Assets',
value: function Assets(uid) {
this.type = 'asset';
if (uid && typeof uid === "string") {
var asset = new _assets2.default();
asset.asset_uid = uid;
return Utils.merge(asset, this);
}
return this;
}
/**
* @method Query
* @description Query instance to provide support for all search queries.
* @example ContentType('blog').Query()
* @returns {Query}
*/
}, {
key: 'Query',
value: function Query() {
var query = new _query2.default();
return Utils.merge(query, this);
}
/**
* @method getLastActivites
* @description getLastActivites get all the ContentTypes whose last activity updated.
* @example Stack.getLastActivites()
* @returns {Stack}
* @ignore
*/
}, {
key: 'getLastActivities',
value: function getLastActivities() {
var query = {
method: 'POST',
headers: this.headers,
url: this.config.protocol + "://" + this.config.host + ':' + this.config.port + '/' + this.config.version + this.config.urls.content_types,
body: {
_method: 'GET',
only_last_activity: true,
environment: this.environment
}
};
return (0, _request2.default)(query);
}
/**
* @method sync
* @description The Sync API takes care of syncing your Contentstack data with your app and ensures that the data is always up-to-date by providing delta updates. Contentstack’s iOS SDK supports Sync API, which you can use to build powerful apps. Read through to understand how to use the Sync API with Contentstack JavaScript SDK.
* @param {object} params - params is an object which Supports locale, start_date, content_type_id queries.
* @example
* Stack.sync({'init': true}) // For initializing sync
* @example
* Stack.sync({'init': true, 'locale': 'en-us'}) //For initializing sync with entries of a specific locale
* @example
* Stack.sync({'init': true, 'start_date': '2018-10-22'}) //For initializing sync with entries published after a specific date
* @example
* Stack.sync({'init': true, 'content_type_id': 'session'}) //For initializing sync with entries of a specific content type
* @example
* Stack.sync({'init': true, 'type': 'entry_published'}) //Use the type parameter to get a specific type of content.Supports 'asset_published', 'entry_published', 'asset_unpublished', 'entry_unpublished', 'asset_deleted', 'entry_deleted', 'content_type_deleted'.
* @example
* Stack.sync({'pagination_token': '<btlsomething>'}) // For fetching the next batch of entries using pagination token
* @example
* Stack.sync({'sync_token': '<btlsomething>'}) // For performing subsequent sync after initial sync
* @returns {object}
*/
}, {
key: 'sync',
value: function sync(params) {
this._query = {};
this._query = Object.assign(this._query, params);
this.requestParams = {
method: 'POST',
headers: this.headers,
url: this.config.protocol + "://" + this.config.host + ':' + this.config.port + '/' + this.config.version + this.config.urls.sync,
body: {
_method: 'GET',
query: this._query
}
};
return Utils.sendRequest(this);
}
/**
* @method imageTransform
* @description Transforms provided image url based on transformation parameters.
* @param {String} url - Url on which transformations to be applied.
* @param {String} params - Transformation parameters
* @example
* Stack.imageTransform(imageURL, {height: 100, width: 200, disable: "upscale"});
* @example
* Stack.imageTransform(imageURL, {crop: "150,100"});
* @example
* Stack.imageTransform(imageURL, {format: "png", crop: "150,100"});
* @returns {string} [Image url with transformation parameters.]
*/
}, {
key: 'imageTransform',
value: function imageTransform(url, params) {
if (url && typeof url === "string" && (typeof params === 'undefined' ? 'undefined' : _typeof(params)) === "object" && params.length === undefined) {
var queryParams = [];
for (var operation in params) {
queryParams.push(operation + '=' + params[operation]);
}
url += url.indexOf("?") <= -1 ? "?" + queryParams.join('&') : "&" + queryParams.join('&');
}
return url;
}
}]);
return Stack;
}();
exports.default = Stack;
/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
exports.default = Request;
var _utils = __webpack_require__(0);
var Utils = _interopRequireWildcard(_utils);
var _http = __webpack_require__(15);
var _http2 = _interopRequireDefault(_http);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
//JS SDK version
var version = '3.4.1';
var environment = void 0,
api_key = void 0;
function Request(options) {
return new Promise(function (resolve, reject) {
var queryParams = void 0;
var serialize = function serialize(obj, prefix) {
var str = [],
p = void 0;
if ((typeof obj === "undefined" ? "undefined" : _typeof(obj)) === "object" && obj.length !== undefined) {
for (var i = 0, _i = obj.length; i < _i; i++) {
str.push(prefix + '[]=' + obj[i]);
}
} else {
for (p in obj) {
var k = prefix ? prefix + "[" + p + "]" : p,
v = obj[p];
str.push(v !== null && (typeof v === "undefined" ? "undefined" : _typeof(v)) === "object" && p !== 'query' ? serialize(v, k) : k + "=" + encodeURIComponent(p !== 'query' ? v : JSON.stringify(v)));
}
}
return str.join("&");
};
var url = options.url,
headers = options.headers;
// setting headers
headers['Content-Type'] = 'application/json; charset=UTF-8';
headers['X-User-Agent'] = 'contentstack-react-native/' + version;
if (options.body && _typeof(options.body) === 'object') {
delete options.body._method;
if (_typeof(options.body.query) === "object" && Object.keys(options.body.query).length === 0) delete options.body.query;
queryParams = serialize(options.body);
}
(0, _http2.default)(url + '?' + queryParams, {
method: 'GET',
headers: headers
}).then(function (response) {
if (response.ok && response.status === 200) {
var data = response.json();
resolve(data);
} else {