forked from Airtable/airtable.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
airtable.browser.js
3753 lines (3353 loc) · 118 KB
/
airtable.browser.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=(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
"use strict";
// istanbul ignore file
var AbortController;
var browserGlobal = typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : null; // self is the global in web workers
if (!browserGlobal) {
AbortController = require('abort-controller');
}
else if ('signal' in new Request('https://airtable.com')) {
AbortController = browserGlobal.AbortController;
}
else {
/* eslint-disable @typescript-eslint/no-var-requires */
var polyfill = require('abortcontroller-polyfill/dist/cjs-ponyfill');
/* eslint-enable @typescript-eslint/no-var-requires */
AbortController = polyfill.AbortController;
}
module.exports = AbortController;
},{"abort-controller":20,"abortcontroller-polyfill/dist/cjs-ponyfill":19}],2:[function(require,module,exports){
"use strict";
var AirtableError = /** @class */ (function () {
function AirtableError(error, message, statusCode) {
this.error = error;
this.message = message;
this.statusCode = statusCode;
}
AirtableError.prototype.toString = function () {
return [
this.message,
'(',
this.error,
')',
this.statusCode ? "[Http code " + this.statusCode + "]" : '',
].join('');
};
return AirtableError;
}());
module.exports = AirtableError;
},{}],3:[function(require,module,exports){
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
var get_1 = __importDefault(require("lodash/get"));
var isPlainObject_1 = __importDefault(require("lodash/isPlainObject"));
var keys_1 = __importDefault(require("lodash/keys"));
var fetch_1 = __importDefault(require("./fetch"));
var abort_controller_1 = __importDefault(require("./abort-controller"));
var object_to_query_param_string_1 = __importDefault(require("./object_to_query_param_string"));
var airtable_error_1 = __importDefault(require("./airtable_error"));
var table_1 = __importDefault(require("./table"));
var http_headers_1 = __importDefault(require("./http_headers"));
var run_action_1 = __importDefault(require("./run_action"));
var package_version_1 = __importDefault(require("./package_version"));
var exponential_backoff_with_jitter_1 = __importDefault(require("./exponential_backoff_with_jitter"));
var userAgent = "Airtable.js/" + package_version_1.default;
var Base = /** @class */ (function () {
function Base(airtable, baseId) {
this._airtable = airtable;
this._id = baseId;
}
Base.prototype.table = function (tableName) {
return new table_1.default(this, null, tableName);
};
Base.prototype.makeRequest = function (options) {
var _this = this;
var _a;
if (options === void 0) { options = {}; }
var method = get_1.default(options, 'method', 'GET').toUpperCase();
var url = this._airtable._endpointUrl + "/v" + this._airtable._apiVersionMajor + "/" + this._id + get_1.default(options, 'path', '/') + "?" + object_to_query_param_string_1.default(get_1.default(options, 'qs', {}));
var controller = new abort_controller_1.default();
var headers = this._getRequestHeaders(Object.assign({}, this._airtable._customHeaders, (_a = options.headers) !== null && _a !== void 0 ? _a : {}));
var requestOptions = {
method: method,
headers: headers,
signal: controller.signal,
};
if ('body' in options && _canRequestMethodIncludeBody(method)) {
requestOptions.body = JSON.stringify(options.body);
}
var timeout = setTimeout(function () {
controller.abort();
}, this._airtable._requestTimeout);
return new Promise(function (resolve, reject) {
fetch_1.default(url, requestOptions)
.then(function (resp) {
clearTimeout(timeout);
if (resp.status === 429 && !_this._airtable._noRetryIfRateLimited) {
var numAttempts_1 = get_1.default(options, '_numAttempts', 0);
var backoffDelayMs = exponential_backoff_with_jitter_1.default(numAttempts_1);
setTimeout(function () {
var newOptions = __assign(__assign({}, options), { _numAttempts: numAttempts_1 + 1 });
_this.makeRequest(newOptions)
.then(resolve)
.catch(reject);
}, backoffDelayMs);
}
else {
resp.json()
.then(function (body) {
var err = _this._checkStatusForError(resp.status, body) ||
_getErrorForNonObjectBody(resp.status, body);
if (err) {
reject(err);
}
else {
resolve({
statusCode: resp.status,
headers: resp.headers,
body: body,
});
}
})
.catch(function () {
var err = _getErrorForNonObjectBody(resp.status);
reject(err);
});
}
})
.catch(function (err) {
clearTimeout(timeout);
err = new airtable_error_1.default('CONNECTION_ERROR', err.message, null);
reject(err);
});
});
};
/**
* @deprecated This method is deprecated.
*/
Base.prototype.runAction = function (method, path, queryParams, bodyData, callback) {
run_action_1.default(this, method, path, queryParams, bodyData, callback, 0);
};
Base.prototype._getRequestHeaders = function (headers) {
var result = new http_headers_1.default();
result.set('Authorization', "Bearer " + this._airtable._apiKey);
result.set('User-Agent', userAgent);
result.set('Content-Type', 'application/json');
for (var _i = 0, _a = keys_1.default(headers); _i < _a.length; _i++) {
var headerKey = _a[_i];
result.set(headerKey, headers[headerKey]);
}
return result.toJSON();
};
Base.prototype._checkStatusForError = function (statusCode, body) {
var _a = (body !== null && body !== void 0 ? body : { error: {} }).error, error = _a === void 0 ? {} : _a;
var type = error.type, message = error.message;
if (statusCode === 401) {
return new airtable_error_1.default('AUTHENTICATION_REQUIRED', 'You should provide valid api key to perform this operation', statusCode);
}
else if (statusCode === 403) {
return new airtable_error_1.default('NOT_AUTHORIZED', 'You are not authorized to perform this operation', statusCode);
}
else if (statusCode === 404) {
return new airtable_error_1.default('NOT_FOUND', message !== null && message !== void 0 ? message : 'Could not find what you are looking for', statusCode);
}
else if (statusCode === 413) {
return new airtable_error_1.default('REQUEST_TOO_LARGE', 'Request body is too large', statusCode);
}
else if (statusCode === 422) {
return new airtable_error_1.default(type !== null && type !== void 0 ? type : 'UNPROCESSABLE_ENTITY', message !== null && message !== void 0 ? message : 'The operation cannot be processed', statusCode);
}
else if (statusCode === 429) {
return new airtable_error_1.default('TOO_MANY_REQUESTS', 'You have made too many requests in a short period of time. Please retry your request later', statusCode);
}
else if (statusCode === 500) {
return new airtable_error_1.default('SERVER_ERROR', 'Try again. If the problem persists, contact support.', statusCode);
}
else if (statusCode === 503) {
return new airtable_error_1.default('SERVICE_UNAVAILABLE', 'The service is temporarily unavailable. Please retry shortly.', statusCode);
}
else if (statusCode >= 400) {
return new airtable_error_1.default(type !== null && type !== void 0 ? type : 'UNEXPECTED_ERROR', message !== null && message !== void 0 ? message : 'An unexpected error occurred', statusCode);
}
else {
return null;
}
};
Base.prototype.doCall = function (tableName) {
return this.table(tableName);
};
Base.prototype.getId = function () {
return this._id;
};
Base.createFunctor = function (airtable, baseId) {
var base = new Base(airtable, baseId);
var baseFn = function (tableName) {
return base.doCall(tableName);
};
baseFn._base = base;
baseFn.table = base.table.bind(base);
baseFn.makeRequest = base.makeRequest.bind(base);
baseFn.runAction = base.runAction.bind(base);
baseFn.getId = base.getId.bind(base);
return baseFn;
};
return Base;
}());
function _canRequestMethodIncludeBody(method) {
return method !== 'GET' && method !== 'DELETE';
}
function _getErrorForNonObjectBody(statusCode, body) {
if (isPlainObject_1.default(body)) {
return null;
}
else {
return new airtable_error_1.default('UNEXPECTED_ERROR', 'The response from Airtable was invalid JSON. Please try again soon.', statusCode);
}
}
module.exports = Base;
},{"./abort-controller":1,"./airtable_error":2,"./exponential_backoff_with_jitter":6,"./fetch":7,"./http_headers":9,"./object_to_query_param_string":11,"./package_version":12,"./run_action":16,"./table":17,"lodash/get":77,"lodash/isPlainObject":89,"lodash/keys":93}],4:[function(require,module,exports){
"use strict";
/**
* Given a function fn that takes a callback as its last argument, returns
* a new version of the function that takes the callback optionally. If
* the function is not called with a callback for the last argument, the
* function will return a promise instead.
*/
/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types */
function callbackToPromise(fn, context, callbackArgIndex) {
if (callbackArgIndex === void 0) { callbackArgIndex = void 0; }
/* eslint-enable @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types */
return function () {
var callArgs = [];
for (var _i = 0; _i < arguments.length; _i++) {
callArgs[_i] = arguments[_i];
}
var thisCallbackArgIndex;
if (callbackArgIndex === void 0) {
// istanbul ignore next
thisCallbackArgIndex = callArgs.length > 0 ? callArgs.length - 1 : 0;
}
else {
thisCallbackArgIndex = callbackArgIndex;
}
var callbackArg = callArgs[thisCallbackArgIndex];
if (typeof callbackArg === 'function') {
fn.apply(context, callArgs);
return void 0;
}
else {
var args_1 = [];
// If an explicit callbackArgIndex is set, but the function is called
// with too few arguments, we want to push undefined onto args so that
// our constructed callback ends up at the right index.
var argLen = Math.max(callArgs.length, thisCallbackArgIndex);
for (var i = 0; i < argLen; i++) {
args_1.push(callArgs[i]);
}
return new Promise(function (resolve, reject) {
args_1.push(function (err, result) {
if (err) {
reject(err);
}
else {
resolve(result);
}
});
fn.apply(context, args_1);
});
}
};
}
module.exports = callbackToPromise;
},{}],5:[function(require,module,exports){
"use strict";
var didWarnForDeprecation = {};
/**
* Convenience function for marking a function as deprecated.
*
* Will emit a warning the first time that function is called.
*
* @param fn the function to mark as deprecated.
* @param key a unique key identifying the function.
* @param message the warning message.
*
* @return a wrapped function
*/
function deprecate(fn, key, message) {
return function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
if (!didWarnForDeprecation[key]) {
didWarnForDeprecation[key] = true;
console.warn(message);
}
fn.apply(this, args);
};
}
module.exports = deprecate;
},{}],6:[function(require,module,exports){
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
var internal_config_json_1 = __importDefault(require("./internal_config.json"));
// "Full Jitter" algorithm taken from https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/
function exponentialBackoffWithJitter(numberOfRetries) {
var rawBackoffTimeMs = internal_config_json_1.default.INITIAL_RETRY_DELAY_IF_RATE_LIMITED * Math.pow(2, numberOfRetries);
var clippedBackoffTimeMs = Math.min(internal_config_json_1.default.MAX_RETRY_DELAY_IF_RATE_LIMITED, rawBackoffTimeMs);
var jitteredBackoffTimeMs = Math.random() * clippedBackoffTimeMs;
return jitteredBackoffTimeMs;
}
module.exports = exponentialBackoffWithJitter;
},{"./internal_config.json":10}],7:[function(require,module,exports){
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
// istanbul ignore file
var node_fetch_1 = __importDefault(require("node-fetch"));
var browserGlobal = typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : null; // self is the global in web workers
module.exports = !browserGlobal ? node_fetch_1.default : browserGlobal.fetch.bind(browserGlobal);
},{"node-fetch":20}],8:[function(require,module,exports){
"use strict";
/* eslint-enable @typescript-eslint/no-explicit-any */
function has(object, property) {
return Object.prototype.hasOwnProperty.call(object, property);
}
module.exports = has;
},{}],9:[function(require,module,exports){
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
var keys_1 = __importDefault(require("lodash/keys"));
var isBrowser = typeof window !== 'undefined';
var HttpHeaders = /** @class */ (function () {
function HttpHeaders() {
this._headersByLowercasedKey = {};
}
HttpHeaders.prototype.set = function (headerKey, headerValue) {
var lowercasedKey = headerKey.toLowerCase();
if (lowercasedKey === 'x-airtable-user-agent') {
lowercasedKey = 'user-agent';
headerKey = 'User-Agent';
}
this._headersByLowercasedKey[lowercasedKey] = {
headerKey: headerKey,
headerValue: headerValue,
};
};
HttpHeaders.prototype.toJSON = function () {
var result = {};
for (var _i = 0, _a = keys_1.default(this._headersByLowercasedKey); _i < _a.length; _i++) {
var lowercasedKey = _a[_i];
var headerDefinition = this._headersByLowercasedKey[lowercasedKey];
var headerKey = void 0;
/* istanbul ignore next */
if (isBrowser && lowercasedKey === 'user-agent') {
// Some browsers do not allow overriding the user agent.
// https://github.com/Airtable/airtable.js/issues/52
headerKey = 'X-Airtable-User-Agent';
}
else {
headerKey = headerDefinition.headerKey;
}
result[headerKey] = headerDefinition.headerValue;
}
return result;
};
return HttpHeaders;
}());
module.exports = HttpHeaders;
},{"lodash/keys":93}],10:[function(require,module,exports){
module.exports={
"INITIAL_RETRY_DELAY_IF_RATE_LIMITED": 5000,
"MAX_RETRY_DELAY_IF_RATE_LIMITED": 600000
}
},{}],11:[function(require,module,exports){
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
var isArray_1 = __importDefault(require("lodash/isArray"));
var isNil_1 = __importDefault(require("lodash/isNil"));
var keys_1 = __importDefault(require("lodash/keys"));
/* eslint-enable @typescript-eslint/no-explicit-any */
// Adapted from jQuery.param:
// https://github.com/jquery/jquery/blob/2.2-stable/src/serialize.js
function buildParams(prefix, obj, addFn) {
if (isArray_1.default(obj)) {
// Serialize array item.
for (var index = 0; index < obj.length; index++) {
var value = obj[index];
if (/\[\]$/.test(prefix)) {
// Treat each array item as a scalar.
addFn(prefix, value);
}
else {
// Item is non-scalar (array or object), encode its numeric index.
buildParams(prefix + "[" + (typeof value === 'object' && value !== null ? index : '') + "]", value, addFn);
}
}
}
else if (typeof obj === 'object') {
// Serialize object item.
for (var _i = 0, _a = keys_1.default(obj); _i < _a.length; _i++) {
var key = _a[_i];
var value = obj[key];
buildParams(prefix + "[" + key + "]", value, addFn);
}
}
else {
// Serialize scalar item.
addFn(prefix, obj);
}
}
function objectToQueryParamString(obj) {
var parts = [];
var addFn = function (key, value) {
value = isNil_1.default(value) ? '' : value;
parts.push(encodeURIComponent(key) + "=" + encodeURIComponent(value));
};
for (var _i = 0, _a = keys_1.default(obj); _i < _a.length; _i++) {
var key = _a[_i];
var value = obj[key];
buildParams(key, value, addFn);
}
return parts.join('&').replace(/%20/g, '+');
}
module.exports = objectToQueryParamString;
},{"lodash/isArray":79,"lodash/isNil":85,"lodash/keys":93}],12:[function(require,module,exports){
"use strict";
module.exports = "0.12.2";
},{}],13:[function(require,module,exports){
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
var isFunction_1 = __importDefault(require("lodash/isFunction"));
var keys_1 = __importDefault(require("lodash/keys"));
var record_1 = __importDefault(require("./record"));
var callback_to_promise_1 = __importDefault(require("./callback_to_promise"));
var has_1 = __importDefault(require("./has"));
var query_params_1 = require("./query_params");
var object_to_query_param_string_1 = __importDefault(require("./object_to_query_param_string"));
/**
* Builds a query object. Won't fetch until `firstPage` or
* or `eachPage` is called.
*
* Params should be validated prior to being passed to Query
* with `Query.validateParams`.
*/
var Query = /** @class */ (function () {
function Query(table, params) {
this._table = table;
this._params = params;
this.firstPage = callback_to_promise_1.default(firstPage, this);
this.eachPage = callback_to_promise_1.default(eachPage, this, 1);
this.all = callback_to_promise_1.default(all, this);
}
/**
* Validates the parameters for passing to the Query constructor.
*
* @params {object} params parameters to validate
*
* @return an object with two keys:
* validParams: the object that should be passed to the constructor.
* ignoredKeys: a list of keys that will be ignored.
* errors: a list of error messages.
*/
Query.validateParams = function (params) {
var validParams = {};
var ignoredKeys = [];
var errors = [];
for (var _i = 0, _a = keys_1.default(params); _i < _a.length; _i++) {
var key = _a[_i];
var value = params[key];
if (has_1.default(Query.paramValidators, key)) {
var validator = Query.paramValidators[key];
var validationResult = validator(value);
if (validationResult.pass) {
validParams[key] = value;
}
else {
errors.push(validationResult.error);
}
}
else {
ignoredKeys.push(key);
}
}
return {
validParams: validParams,
ignoredKeys: ignoredKeys,
errors: errors,
};
};
Query.paramValidators = query_params_1.paramValidators;
return Query;
}());
/**
* Fetches the first page of results for the query asynchronously,
* then calls `done(error, records)`.
*/
function firstPage(done) {
if (!isFunction_1.default(done)) {
throw new Error('The first parameter to `firstPage` must be a function');
}
this.eachPage(function (records) {
done(null, records);
}, function (error) {
done(error, null);
});
}
/**
* Fetches each page of results for the query asynchronously.
*
* Calls `pageCallback(records, fetchNextPage)` for each
* page. You must call `fetchNextPage()` to fetch the next page of
* results.
*
* After fetching all pages, or if there's an error, calls
* `done(error)`.
*/
function eachPage(pageCallback, done) {
var _this = this;
if (!isFunction_1.default(pageCallback)) {
throw new Error('The first parameter to `eachPage` must be a function');
}
if (!isFunction_1.default(done) && done !== void 0) {
throw new Error('The second parameter to `eachPage` must be a function or undefined');
}
var params = __assign({}, this._params);
var pathAndParamsAsString = "/" + this._table._urlEncodedNameOrId() + "?" + object_to_query_param_string_1.default(params);
var queryParams = {};
var requestData = null;
var method;
var path;
if (params.method === 'post' || pathAndParamsAsString.length > query_params_1.URL_CHARACTER_LENGTH_LIMIT) {
// There is a 16kb limit on GET requests. Since the URL makes up nearly all of the request size, we check for any requests that
// that come close to this limit and send it as a POST instead. Additionally, we'll send the request as a post if it is specified
// with the request params
requestData = params;
method = 'post';
path = "/" + this._table._urlEncodedNameOrId() + "/listRecords";
var paramNames = Object.keys(params);
for (var _i = 0, paramNames_1 = paramNames; _i < paramNames_1.length; _i++) {
var paramName = paramNames_1[_i];
if (query_params_1.shouldListRecordsParamBePassedAsParameter(paramName)) {
// timeZone and userLocale is parsed from the GET request separately from the other params. This parsing
// does not occurring within the body parser we use for POST requests, so this will still need to be passed
// via query params
queryParams[paramName] = params[paramName];
}
else {
requestData[paramName] = params[paramName];
}
}
}
else {
method = 'get';
queryParams = params;
path = "/" + this._table._urlEncodedNameOrId();
}
var inner = function () {
_this._table._base.runAction(method, path, queryParams, requestData, function (err, response, result) {
if (err) {
done(err, null);
}
else {
var next = void 0;
if (result.offset) {
params.offset = result.offset;
next = inner;
}
else {
next = function () {
done(null);
};
}
var records = result.records.map(function (recordJson) {
return new record_1.default(_this._table, null, recordJson);
});
pageCallback(records, next);
}
});
};
inner();
}
/**
* Fetches all pages of results asynchronously. May take a long time.
*/
function all(done) {
if (!isFunction_1.default(done)) {
throw new Error('The first parameter to `all` must be a function');
}
var allRecords = [];
this.eachPage(function (pageRecords, fetchNextPage) {
allRecords.push.apply(allRecords, pageRecords);
fetchNextPage();
}, function (err) {
if (err) {
done(err, null);
}
else {
done(null, allRecords);
}
});
}
module.exports = Query;
},{"./callback_to_promise":4,"./has":8,"./object_to_query_param_string":11,"./query_params":14,"./record":15,"lodash/isFunction":83,"lodash/keys":93}],14:[function(require,module,exports){
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.shouldListRecordsParamBePassedAsParameter = exports.URL_CHARACTER_LENGTH_LIMIT = exports.paramValidators = void 0;
var typecheck_1 = __importDefault(require("./typecheck"));
var isString_1 = __importDefault(require("lodash/isString"));
var isNumber_1 = __importDefault(require("lodash/isNumber"));
var isPlainObject_1 = __importDefault(require("lodash/isPlainObject"));
var isBoolean_1 = __importDefault(require("lodash/isBoolean"));
exports.paramValidators = {
fields: typecheck_1.default(typecheck_1.default.isArrayOf(isString_1.default), 'the value for `fields` should be an array of strings'),
filterByFormula: typecheck_1.default(isString_1.default, 'the value for `filterByFormula` should be a string'),
maxRecords: typecheck_1.default(isNumber_1.default, 'the value for `maxRecords` should be a number'),
pageSize: typecheck_1.default(isNumber_1.default, 'the value for `pageSize` should be a number'),
offset: typecheck_1.default(isNumber_1.default, 'the value for `offset` should be a number'),
sort: typecheck_1.default(typecheck_1.default.isArrayOf(function (obj) {
return (isPlainObject_1.default(obj) &&
isString_1.default(obj.field) &&
(obj.direction === void 0 || ['asc', 'desc'].includes(obj.direction)));
}), 'the value for `sort` should be an array of sort objects. ' +
'Each sort object must have a string `field` value, and an optional ' +
'`direction` value that is "asc" or "desc".'),
view: typecheck_1.default(isString_1.default, 'the value for `view` should be a string'),
cellFormat: typecheck_1.default(function (cellFormat) {
return isString_1.default(cellFormat) && ['json', 'string'].includes(cellFormat);
}, 'the value for `cellFormat` should be "json" or "string"'),
timeZone: typecheck_1.default(isString_1.default, 'the value for `timeZone` should be a string'),
userLocale: typecheck_1.default(isString_1.default, 'the value for `userLocale` should be a string'),
method: typecheck_1.default(function (method) {
return isString_1.default(method) && ['get', 'post'].includes(method);
}, 'the value for `method` should be "get" or "post"'),
returnFieldsByFieldId: typecheck_1.default(isBoolean_1.default, 'the value for `returnFieldsByFieldId` should be a boolean'),
recordMetadata: typecheck_1.default(typecheck_1.default.isArrayOf(isString_1.default), 'the value for `recordMetadata` should be an array of strings'),
};
exports.URL_CHARACTER_LENGTH_LIMIT = 15000;
exports.shouldListRecordsParamBePassedAsParameter = function (paramName) {
return paramName === 'timeZone' || paramName === 'userLocale';
};
},{"./typecheck":18,"lodash/isBoolean":81,"lodash/isNumber":86,"lodash/isPlainObject":89,"lodash/isString":90}],15:[function(require,module,exports){
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
var callback_to_promise_1 = __importDefault(require("./callback_to_promise"));
var Record = /** @class */ (function () {
function Record(table, recordId, recordJson) {
this._table = table;
this.id = recordId || recordJson.id;
if (recordJson) {
this.commentCount = recordJson.commentCount;
}
this.setRawJson(recordJson);
this.save = callback_to_promise_1.default(save, this);
this.patchUpdate = callback_to_promise_1.default(patchUpdate, this);
this.putUpdate = callback_to_promise_1.default(putUpdate, this);
this.destroy = callback_to_promise_1.default(destroy, this);
this.fetch = callback_to_promise_1.default(fetch, this);
this.updateFields = this.patchUpdate;
this.replaceFields = this.putUpdate;
}
Record.prototype.getId = function () {
return this.id;
};
Record.prototype.get = function (columnName) {
return this.fields[columnName];
};
Record.prototype.set = function (columnName, columnValue) {
this.fields[columnName] = columnValue;
};
Record.prototype.setRawJson = function (rawJson) {
this._rawJson = rawJson;
this.fields = (this._rawJson && this._rawJson.fields) || {};
};
return Record;
}());
function save(done) {
this.putUpdate(this.fields, done);
}
function patchUpdate(cellValuesByName, opts, done) {
var _this = this;
if (!done) {
done = opts;
opts = {};
}
var updateBody = __assign({ fields: cellValuesByName }, opts);
this._table._base.runAction('patch', "/" + this._table._urlEncodedNameOrId() + "/" + this.id, {}, updateBody, function (err, response, results) {
if (err) {
done(err);
return;
}
_this.setRawJson(results);
done(null, _this);
});
}
function putUpdate(cellValuesByName, opts, done) {
var _this = this;
if (!done) {
done = opts;
opts = {};
}
var updateBody = __assign({ fields: cellValuesByName }, opts);
this._table._base.runAction('put', "/" + this._table._urlEncodedNameOrId() + "/" + this.id, {}, updateBody, function (err, response, results) {
if (err) {
done(err);
return;
}
_this.setRawJson(results);
done(null, _this);
});
}
function destroy(done) {
var _this = this;
this._table._base.runAction('delete', "/" + this._table._urlEncodedNameOrId() + "/" + this.id, {}, null, function (err) {
if (err) {
done(err);
return;
}
done(null, _this);
});
}
function fetch(done) {
var _this = this;
this._table._base.runAction('get', "/" + this._table._urlEncodedNameOrId() + "/" + this.id, {}, null, function (err, response, results) {
if (err) {
done(err);
return;
}
_this.setRawJson(results);
done(null, _this);
});
}
module.exports = Record;
},{"./callback_to_promise":4}],16:[function(require,module,exports){
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
var exponential_backoff_with_jitter_1 = __importDefault(require("./exponential_backoff_with_jitter"));
var object_to_query_param_string_1 = __importDefault(require("./object_to_query_param_string"));
var package_version_1 = __importDefault(require("./package_version"));
var fetch_1 = __importDefault(require("./fetch"));
var abort_controller_1 = __importDefault(require("./abort-controller"));
var userAgent = "Airtable.js/" + package_version_1.default;
function runAction(base, method, path, queryParams, bodyData, callback, numAttempts) {
var url = base._airtable._endpointUrl + "/v" + base._airtable._apiVersionMajor + "/" + base._id + path + "?" + object_to_query_param_string_1.default(queryParams);
var headers = {
authorization: "Bearer " + base._airtable._apiKey,
'x-api-version': base._airtable._apiVersion,
'x-airtable-application-id': base.getId(),
'content-type': 'application/json',
};
var isBrowser = typeof window !== 'undefined';
// Some browsers do not allow overriding the user agent.
// https://github.com/Airtable/airtable.js/issues/52
if (isBrowser) {
headers['x-airtable-user-agent'] = userAgent;
}
else {
headers['User-Agent'] = userAgent;
}
var controller = new abort_controller_1.default();
var normalizedMethod = method.toUpperCase();
var options = {
method: normalizedMethod,
headers: headers,
signal: controller.signal,
};
if (bodyData !== null) {
if (normalizedMethod === 'GET' || normalizedMethod === 'HEAD') {
console.warn('body argument to runAction are ignored with GET or HEAD requests');
}
else {
options.body = JSON.stringify(bodyData);
}
}
var timeout = setTimeout(function () {
controller.abort();
}, base._airtable._requestTimeout);
fetch_1.default(url, options)
.then(function (resp) {
clearTimeout(timeout);
if (resp.status === 429 && !base._airtable._noRetryIfRateLimited) {
var backoffDelayMs = exponential_backoff_with_jitter_1.default(numAttempts);
setTimeout(function () {
runAction(base, method, path, queryParams, bodyData, callback, numAttempts + 1);
}, backoffDelayMs);
}
else {
resp.json()
.then(function (body) {
var error = base._checkStatusForError(resp.status, body);
// Ensure Response interface matches interface from
// `request` Response object
var r = {};
Object.keys(resp).forEach(function (property) {
r[property] = resp[property];
});
r.body = body;
r.statusCode = resp.status;
callback(error, r, body);
})
.catch(function () {
callback(base._checkStatusForError(resp.status));
});
}
})
.catch(function (error) {
clearTimeout(timeout);
callback(error);
});
}
module.exports = runAction;
},{"./abort-controller":1,"./exponential_backoff_with_jitter":6,"./fetch":7,"./object_to_query_param_string":11,"./package_version":12}],17:[function(require,module,exports){
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
var isPlainObject_1 = __importDefault(require("lodash/isPlainObject"));
var deprecate_1 = __importDefault(require("./deprecate"));
var query_1 = __importDefault(require("./query"));
var query_params_1 = require("./query_params");
var object_to_query_param_string_1 = __importDefault(require("./object_to_query_param_string"));
var record_1 = __importDefault(require("./record"));
var callback_to_promise_1 = __importDefault(require("./callback_to_promise"));
var Table = /** @class */ (function () {
function Table(base, tableId, tableName) {
if (!tableId && !tableName) {
throw new Error('Table name or table ID is required');
}
this._base = base;
this.id = tableId;
this.name = tableName;
// Public API
this.find = callback_to_promise_1.default(this._findRecordById, this);
this.select = this._selectRecords.bind(this);
this.create = callback_to_promise_1.default(this._createRecords, this);
this.update = callback_to_promise_1.default(this._updateRecords.bind(this, false), this);
this.replace = callback_to_promise_1.default(this._updateRecords.bind(this, true), this);
this.destroy = callback_to_promise_1.default(this._destroyRecord, this);
// Deprecated API
this.list = deprecate_1.default(this._listRecords.bind(this), 'table.list', 'Airtable: `list()` is deprecated. Use `select()` instead.');
this.forEach = deprecate_1.default(this._forEachRecord.bind(this), 'table.forEach', 'Airtable: `forEach()` is deprecated. Use `select()` instead.');
}
Table.prototype._findRecordById = function (recordId, done) {
var record = new record_1.default(this, recordId);
record.fetch(done);
};
Table.prototype._selectRecords = function (params) {
if (params === void 0) {
params = {};
}
if (arguments.length > 1) {
console.warn("Airtable: `select` takes only one parameter, but it was given " + arguments.length + " parameters. Use `eachPage` or `firstPage` to fetch records.");
}
if (isPlainObject_1.default(params)) {
var validationResults = query_1.default.validateParams(params);
if (validationResults.errors.length) {
var formattedErrors = validationResults.errors.map(function (error) {
return " * " + error;
});
throw new Error("Airtable: invalid parameters for `select`:\n" + formattedErrors.join('\n'));
}
if (validationResults.ignoredKeys.length) {
console.warn("Airtable: the following parameters to `select` will be ignored: " + validationResults.ignoredKeys.join(', '));
}
return new query_1.default(this, validationResults.validParams);
}
else {
throw new Error('Airtable: the parameter for `select` should be a plain object or undefined.');
}
};
Table.prototype._urlEncodedNameOrId = function () {
return this.id || encodeURIComponent(this.name);
};
Table.prototype._createRecords = function (recordsData, optionalParameters, done) {
var _this = this;
var isCreatingMultipleRecords = Array.isArray(recordsData);
if (!done) {
done = optionalParameters;
optionalParameters = {};
}
var requestData;
if (isCreatingMultipleRecords) {
requestData = __assign({ records: recordsData }, optionalParameters);
}
else {
requestData = __assign({ fields: recordsData }, optionalParameters);
}
this._base.runAction('post', "/" + this._urlEncodedNameOrId() + "/", {}, requestData, function (err, resp, body) {
if (err) {
done(err);
return;
}
var result;
if (isCreatingMultipleRecords) {
result = body.records.map(function (record) {
return new record_1.default(_this, record.id, record);
});
}
else {
result = new record_1.default(_this, body.id, body);
}
done(null, result);
});
};
Table.prototype._updateRecords = function (isDestructiveUpdate, recordsDataOrRecordId, recordDataOrOptsOrDone, optsOrDone, done) {
var _this = this;
var opts;
if (Array.isArray(recordsDataOrRecordId)) {
var recordsData = recordsDataOrRecordId;
opts = isPlainObject_1.default(recordDataOrOptsOrDone) ? recordDataOrOptsOrDone : {};
done = (optsOrDone || recordDataOrOptsOrDone);
var method = isDestructiveUpdate ? 'put' : 'patch';
var requestData = __assign({ records: recordsData }, opts);
this._base.runAction(method, "/" + this._urlEncodedNameOrId() + "/", {}, requestData, function (err, resp, body) {
if (err) {
done(err);
return;
}
var result = body.records.map(function (record) {
return new record_1.default(_this, record.id, record);
});
done(null, result);
});
}
else {
var recordId = recordsDataOrRecordId;
var recordData = recordDataOrOptsOrDone;
opts = isPlainObject_1.default(optsOrDone) ? optsOrDone : {};
done = (done || optsOrDone);
var record = new record_1.default(this, recordId);
if (isDestructiveUpdate) {
record.putUpdate(recordData, opts, done);
}