/
test.getch.ts
967 lines (874 loc) · 31.3 KB
/
test.getch.ts
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
// Copyright 2018 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import assert from 'assert';
import nock from 'nock';
import sinon from 'sinon';
import stream, {Readable} from 'stream';
import {describe, it, afterEach} from 'mocha';
import fetch from 'node-fetch';
import {HttpsProxyAgent} from 'https-proxy-agent';
import {
Gaxios,
GaxiosError,
request,
GaxiosOptions,
GaxiosResponse,
GaxiosPromise,
} from '../src';
import {GAXIOS_ERROR_SYMBOL, Headers} from '../src/common';
import {pkg} from '../src/util';
import qs from 'querystring';
import fs from 'fs';
import {Blob} from 'node-fetch';
global.FormData = require('form-data');
nock.disableNetConnect();
const sandbox = sinon.createSandbox();
afterEach(() => {
sandbox.restore();
nock.cleanAll();
});
const url = 'https://example.com';
describe('🦖 option validation', () => {
it('should throw an error if a url is not provided', async () => {
await assert.rejects(request({}), /URL is required/);
});
});
describe('🚙 error handling', () => {
it('should throw on non-2xx responses by default', async () => {
const scope = nock(url).get('/').reply(500);
await assert.rejects(request({url}), (err: GaxiosError) => {
scope.done();
return err.status === 500;
});
});
it('should throw the error as a GaxiosError object, regardless of Content-Type header', async () => {
const body = {
error: {
status: 404,
message: 'File not found',
},
};
const scope = nock(url).get('/').reply(404, body);
await assert.rejects(
request<JSON>({url, responseType: 'json'}),
(err: GaxiosError) => {
scope.done();
return (
err.status === 404 &&
err.message === 'Request failed with status code 404' &&
err.response?.data.error.message === 'File not found'
);
}
);
});
it('should throw the error as a GaxiosError object (with the message as a string), even if the request type is requested as an arraybuffer', async () => {
const body = {
error: {
status: 404,
message: 'File not found',
},
};
const scope = nock(url).get('/').reply(404, body);
await assert.rejects(
request<ArrayBuffer>({url, responseType: 'arraybuffer'}),
(err: GaxiosError) => {
scope.done();
return (
err.status === 404 &&
err.message === 'Request failed with status code 404' &&
err.response?.data.error.message === 'File not found'
);
}
);
});
it('should not throw an error during a translation error', () => {
const notJSON = '.';
const response: GaxiosResponse = {
config: {
responseType: 'json',
},
data: notJSON,
status: 500,
statusText: '',
headers: {},
request: {
responseURL: url,
},
};
const error = new GaxiosError('translation test', {}, response);
assert(error.response, undefined);
assert.equal(error.response.data, notJSON);
});
it('should support `instanceof` for GaxiosErrors of the same version', () => {
class A extends GaxiosError {}
const wrongVersion = {[GAXIOS_ERROR_SYMBOL]: '0.0.0'};
const correctVersion = {[GAXIOS_ERROR_SYMBOL]: pkg.version};
const child = new A('', {});
assert.equal(wrongVersion instanceof GaxiosError, false);
assert.equal(correctVersion instanceof GaxiosError, true);
assert.equal(child instanceof GaxiosError, true);
});
});
describe('🥁 configuration options', () => {
it('should accept URL objects', async () => {
const scope = nock(url).get('/').reply(204);
const res = await request({url: new URL(url)});
scope.done();
assert.strictEqual(res.config.method, 'GET');
});
it('should use options passed into the constructor', async () => {
const scope = nock(url).head('/').reply(200);
const inst = new Gaxios({method: 'HEAD'});
const res = await inst.request({url});
scope.done();
assert.strictEqual(res.config.method, 'HEAD');
});
it('should handle nested options passed into the constructor', async () => {
const scope = nock(url).get('/').reply(200);
const inst = new Gaxios({headers: {apple: 'juice'}});
const res = await inst.request({url, headers: {figgy: 'pudding'}});
scope.done();
assert.strictEqual(res.config.headers!.apple, 'juice');
assert.strictEqual(res.config.headers!.figgy, 'pudding');
});
it('should allow setting a base url in the options', async () => {
const scope = nock(url).get('/v1/mango').reply(200, {});
const inst = new Gaxios({baseURL: `${url}/v1`});
const res = await inst.request({url: '/mango'});
scope.done();
assert.deepStrictEqual(res.data, {});
});
it('should allow overriding valid status', async () => {
const scope = nock(url).get('/').reply(304);
const res = await request({url, validateStatus: () => true});
scope.done();
assert.strictEqual(res.status, 304);
});
it('should allow setting maxContentLength', async () => {
const body = {hello: '🌎'};
const scope = nock(url).get('/').reply(200, body);
const maxContentLength = 1;
await assert.rejects(request({url, maxContentLength}), /over limit/);
scope.done();
});
it('should support redirects by default', async () => {
const body = {hello: '🌎'};
const scopes = [
nock(url).get('/foo').reply(200, body),
nock(url).get('/').reply(302, undefined, {location: '/foo'}),
];
const res = await request({url});
scopes.forEach(x => x.done());
assert.deepStrictEqual(res.data, body);
assert.strictEqual(res.request.responseURL, `${url}/foo`);
});
it('should support disabling redirects', async () => {
const scope = nock(url).get('/').reply(302, undefined, {location: '/foo'});
const maxRedirects = 0;
await assert.rejects(request({url, maxRedirects}), /maximum redirect/);
scope.done();
});
it('should allow overriding the adapter', async () => {
const response: GaxiosResponse = {
data: {hello: '🌎'},
config: {},
status: 200,
statusText: 'OK',
headers: {},
request: {
responseURL: url,
},
};
const adapter = () => Promise.resolve(response);
const res = await request({url, adapter});
assert.strictEqual(response, res);
});
it('should allow overriding the adapter with default adapter wrapper', async () => {
const body = {hello: '🌎'};
const extraProperty = '🦦';
const scope = nock(url).get('/').reply(200, body);
const timings: {duration: number}[] = [];
const res = await request({
url,
adapter: async (opts, defaultAdapter) => {
const begin = Date.now();
const res = await defaultAdapter(opts);
const end = Date.now();
res.data = {
...res.data,
extraProperty,
};
timings.push({duration: end - begin});
return res;
},
});
scope.done();
assert.deepStrictEqual(res.data, {
...body,
extraProperty,
});
assert(timings.length === 1);
assert(typeof timings[0].duration === 'number');
});
it('should encode URL parameters', async () => {
const path = '/?james=kirk&montgomery=scott';
const opts = {url: `${url}${path}`};
const scope = nock(url).get(path).reply(200, {});
const res = await request(opts);
assert.strictEqual(res.status, 200);
assert.strictEqual(res.config.url, url + path);
scope.done();
});
it('should preserve the original querystring', async () => {
const path = '/?robot';
const opts = {url: `${url}${path}`};
const scope = nock(url).get(path).reply(200, {});
const res = await request(opts);
assert.strictEqual(res.status, 200);
assert.strictEqual(res.config.url, url + path);
scope.done();
});
it('should handle empty querystring params', async () => {
const scope = nock(url).get('/').reply(200, {});
const res = await request({
url,
params: {},
});
assert.strictEqual(res.status, 200);
scope.done();
});
it('should encode parameters from the params option', async () => {
const opts = {url, params: {james: 'kirk', montgomery: 'scott'}};
const qs = '?james=kirk&montgomery=scott';
const path = `/${qs}`;
const scope = nock(url).get(path).reply(200, {});
const res = await request(opts);
assert.strictEqual(res.status, 200);
assert.strictEqual(res.config.url, url + qs);
scope.done();
});
it('should merge URL parameters with the params option', async () => {
const opts = {
url: `${url}/?james=beckwith&montgomery=scott`,
params: {james: 'kirk'},
};
const path = '/?james=beckwith&montgomery=scott&james=kirk';
const scope = nock(url).get(path).reply(200, {});
const res = await request(opts);
assert.strictEqual(res.status, 200);
assert.strictEqual(res.config.url, url + path);
scope.done();
});
it('should allow overriding the param serializer', async () => {
const qs = '?oh=HAI';
const params = {james: 'kirk'};
const opts: GaxiosOptions = {
url,
params,
paramsSerializer: ps => {
assert.strictEqual(JSON.stringify(params), JSON.stringify(ps));
return '?oh=HAI';
},
};
const scope = nock(url).get(`/${qs}`).reply(200, {});
const res = await request(opts);
assert.strictEqual(res.status, 200);
assert.strictEqual(res.config.url, url + qs);
scope.done();
});
it('should return json by default', async () => {
const body = {hello: '🌎'};
const scope = nock(url).get('/').reply(200, body);
const res = await request({url});
scope.done();
assert.deepStrictEqual(body, res.data);
});
it('should send an application/json header by default', async () => {
const scope = nock(url)
.matchHeader('accept', 'application/json')
.get('/')
.reply(200, {});
const res = await request({url, responseType: 'json'});
scope.done();
assert.deepStrictEqual(res.data, {});
});
describe('proxying', () => {
it('should use an https proxy if asked nicely', async () => {
const url = 'https://fake.proxy';
sandbox.stub(process, 'env').value({https_proxy: 'https://fake.proxy'});
const body = {hello: '🌎'};
const scope = nock(url).get('/').reply(200, body);
const res = await request({url});
scope.done();
assert.deepStrictEqual(res.data, body);
assert.ok(res.config.agent instanceof HttpsProxyAgent);
});
it('should not proxy when url matches no_proxy', async () => {
const url = 'https://example.com';
sandbox.stub(process, 'env').value({
https_proxy: 'https://fake.proxy',
no_proxy: 'https://example.com',
});
const body = {hello: '🌎'};
const scope = nock(url).get('/').reply(200, body);
const res = await request({url});
scope.done();
assert.deepStrictEqual(res.data, body);
assert.strictEqual(res.config.agent, undefined);
});
it('should proxy if url does not match no_proxy env variable', async () => {
const url = 'https://example2.com';
sandbox.stub(process, 'env').value({
https_proxy: 'https://fake.proxy',
no_proxy: 'https://example.com',
});
const body = {hello: '🌎'};
const scope = nock(url).get('/').reply(200, body);
const res = await request({url});
scope.done();
assert.deepStrictEqual(res.data, body);
assert.ok(res.config.agent instanceof HttpsProxyAgent);
});
it('should not proxy if no_proxy env var matches the origin or hostname of the URL', async () => {
const url = 'https://example2.com';
sandbox.stub(process, 'env').value({
https_proxy: 'https://fake.proxy',
no_proxy: 'example2.com',
});
const body = {hello: '🌎'};
const scope = nock(url).get('/').reply(200, body);
const res = await request({url});
scope.done();
assert.deepStrictEqual(res.data, body);
assert.strictEqual(res.config.agent, undefined);
});
it('should not proxy if no_proxy env variable has asterisk, and URL partially matches', async () => {
const url = 'https://domain.example.com';
sandbox.stub(process, 'env').value({
https_proxy: 'https://fake.proxy',
no_proxy: '*.example.com',
});
const body = {hello: '🌎'};
const scope = nock(url).get('/').reply(200, body);
const res = await request({url});
scope.done();
assert.deepStrictEqual(res.data, body);
assert.strictEqual(res.config.agent, undefined);
});
it('should proxy if no_proxy env variable has asterisk, but URL is not matching', async () => {
const url = 'https://domain.example2.com';
sandbox.stub(process, 'env').value({
https_proxy: 'https://fake.proxy',
no_proxy: '*.example.com',
});
const body = {hello: '🌎'};
const scope = nock(url).get('/').reply(200, body);
const res = await request({url});
scope.done();
assert.deepStrictEqual(res.data, body);
assert.ok(res.config.agent instanceof HttpsProxyAgent);
});
it('should not proxy if no_proxy env variable starts with a dot, and URL partially matches', async () => {
const url = 'https://domain.example.com';
sandbox.stub(process, 'env').value({
https_proxy: 'https://fake.proxy',
no_proxy: '.example.com',
});
const body = {hello: '🌎'};
const scope = nock(url).get('/').reply(200, body);
const res = await request({url});
scope.done();
assert.deepStrictEqual(res.data, body);
assert.strictEqual(res.config.agent, undefined);
});
it('should allow comma-separated lists for no_proxy env variables', async () => {
const url = 'https://api.google.com';
sandbox.stub(process, 'env').value({
https_proxy: 'https://fake.proxy',
no_proxy: 'example.com,*.google.com,hello.com',
});
const body = {hello: '🌎'};
const scope = nock(url).get('/').reply(200, body);
const res = await request({url});
scope.done();
assert.deepStrictEqual(res.data, body);
assert.strictEqual(res.config.agent, undefined);
});
});
it('should load the proxy from the cache', async () => {
sandbox.stub(process, 'env').value({HTTPS_PROXY: 'https://fake.proxy'});
const body = {hello: '🌎'};
const scope = nock(url).get('/').twice().reply(200, body);
const res1 = await request({url});
const agent = res1.config.agent;
const res2 = await request({url});
assert.deepStrictEqual(agent, res2.config.agent);
scope.done();
});
it('should include the request data in the response config', async () => {
const body = {hello: '🌎'};
const scope = nock(url).post('/', body).reply(200);
const res = await request({url, method: 'POST', data: body});
scope.done();
assert.deepStrictEqual(res.config.data, body);
});
it('should not stringify the data if it is appended by a form', async () => {
const formData = new FormData();
formData.append('test', '123');
// I don't think matching formdata is supported in nock, so skipping: https://github.com/nock/nock/issues/887
const scope = nock(url).post('/').reply(200);
const res = await request({
url,
method: 'POST',
data: formData,
});
scope.done();
assert.deepStrictEqual(res.config.data, formData);
assert.ok(res.config.data instanceof FormData);
assert.deepEqual(res.config.body, undefined);
});
it('should allow explicitly setting the fetch implementation to node-fetch', async () => {
const scope = nock(url).get('/').reply(200);
const res = await request({url, fetchImplementation: fetch});
scope.done();
assert.deepStrictEqual(res.status, 200);
});
it('should be able to disable the `errorRedactor`', async () => {
const scope = nock(url).get('/').reply(200);
const instance = new Gaxios({url, errorRedactor: false});
assert.equal(instance.defaults.errorRedactor, false);
await instance.request({url});
scope.done();
assert.equal(instance.defaults.errorRedactor, false);
});
it('should be able to set a custom `errorRedactor`', async () => {
const scope = nock(url).get('/').reply(200);
const errorRedactor = (t: {}) => t;
const instance = new Gaxios({url, errorRedactor});
assert.equal(instance.defaults.errorRedactor, errorRedactor);
await instance.request({url});
scope.done();
assert.equal(instance.defaults.errorRedactor, errorRedactor);
});
});
describe('🎏 data handling', () => {
it('should accpet a ReadableStream as request data', async () => {
const body = fs.createReadStream('package.json');
// eslint-disable-next-line @typescript-eslint/no-var-requires
const contents = require('../../package.json');
const scope = nock(url).post('/', contents).reply(200, {});
const res = await request({url, method: 'POST', data: body});
scope.done();
assert.deepStrictEqual(res.data, {});
});
it('should accept a string in the request data', async () => {
const body = {hello: '🌎'};
const encoded = qs.stringify(body);
const scope = nock(url)
.matchHeader('content-type', 'application/x-www-form-urlencoded')
.post('/', encoded)
.reply(200, {});
const res = await request({
url,
method: 'POST',
data: encoded,
headers: {'content-type': 'application/x-www-form-urlencoded'},
});
scope.done();
assert.deepStrictEqual(res.data, {});
});
it('should set application/json content-type for object request by default', async () => {
const body = {hello: '🌎'};
const scope = nock(url)
.matchHeader('Content-Type', 'application/json')
.post('/', JSON.stringify(body))
.reply(200, {});
const res = await request({
url,
method: 'POST',
data: body,
});
scope.done();
assert.deepStrictEqual(res.data, {});
});
it('should allow other JSON content-types to be specified', async () => {
const body = {hello: '🌎'};
const scope = nock(url)
.matchHeader('Content-Type', 'application/json-patch+json')
.post('/', JSON.stringify(body))
.reply(200, {});
const res = await request({
url,
method: 'POST',
data: body,
headers: {
'Content-Type': 'application/json-patch+json',
},
});
scope.done();
assert.deepStrictEqual(res.data, {});
});
it('should stringify with qs when content-type is set to application/x-www-form-urlencoded', async () => {
const body = {hello: '🌎'};
const scope = nock(url)
.matchHeader('Content-Type', 'application/x-www-form-urlencoded')
.post('/', qs.stringify(body))
.reply(200, {});
const res = await request({
url,
method: 'POST',
data: body,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
});
scope.done();
assert.deepStrictEqual(res.data, {});
});
it('should return stream if asked nicely', async () => {
const body = {hello: '🌎'};
const scope = nock(url).get('/').reply(200, body);
const res = await request<stream.Readable>({url, responseType: 'stream'});
scope.done();
assert(res.data instanceof stream.Readable);
});
it('should return an ArrayBuffer if asked nicely', async () => {
const body = {hello: '🌎'};
const scope = nock(url).get('/').reply(200, body);
const res = await request<ArrayBuffer>({
url,
responseType: 'arraybuffer',
});
scope.done();
assert(res.data instanceof ArrayBuffer);
assert.deepStrictEqual(
Buffer.from(JSON.stringify(body)),
Buffer.from(res.data)
);
});
it('should return a blob if asked nicely', async () => {
const body = {hello: '🌎'};
const scope = nock(url).get('/').reply(200, body);
const res = await request<Blob>({url, responseType: 'blob'});
scope.done();
assert.ok(res.data);
});
it('should return text if asked nicely', async () => {
const body = 'hello 🌎';
const scope = nock(url).get('/').reply(200, body);
const res = await request<string>({url, responseType: 'text'});
scope.done();
assert.strictEqual(res.data, body);
});
it('should return status text', async () => {
const body = {hello: '🌎'};
const scope = nock(url).get('/').reply(200, body);
const res = await request({url});
scope.done();
assert.ok(res.data);
assert.strictEqual(res.statusText, 'OK');
});
it('should return JSON when response Content-Type=application/json', async () => {
const body = {hello: 'world'};
const scope = nock(url)
.get('/')
.reply(200, body, {'Content-Type': 'application/json'});
const res = await request({url});
scope.done();
assert.ok(res.data);
assert.deepStrictEqual(res.data, body);
});
it('should return invalid JSON as text when response Content-Type=application/json', async () => {
const body = 'hello world';
const scope = nock(url)
.get('/')
.reply(200, body, {'Content-Type': 'application/json'});
const res = await request({url});
scope.done();
assert.ok(res.data);
assert.deepStrictEqual(res.data, body);
});
it('should return text when response Content-Type=text/plain', async () => {
const body = 'hello world';
const scope = nock(url)
.get('/')
.reply(200, body, {'Content-Type': 'text/plain'});
const res = await request({url});
scope.done();
assert.ok(res.data);
assert.deepStrictEqual(res.data, body);
});
it('should return text when response Content-Type=text/csv', async () => {
const body = '"col1","col2"\n"hello","world"';
const scope = nock(url)
.get('/')
.reply(200, body, {'Content-Type': 'text/csv'});
const res = await request({url});
scope.done();
assert.ok(res.data);
assert.deepStrictEqual(res.data, body);
});
it('should return raw data when Content-Type is unable to be parsed', async () => {
const body = Buffer.from('hello world', 'utf-8');
const scope = nock(url)
.get('/')
.reply(200, body, {'Content-Type': 'image/gif'});
const res = await request({url});
scope.done();
assert.ok(res.data);
assert.notEqual(res.data, body);
});
it('should handle multipart/related when options.multipart is set and a single part', async () => {
const bodyContent = {hello: '🌎'};
const body = new Readable();
body.push(JSON.stringify(bodyContent));
body.push(null);
const scope = nock(url)
.matchHeader(
'Content-Type',
/multipart\/related; boundary=[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/
)
.post(
'/',
/^(--[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}[\r\n]+Content-Type: application\/json[\r\n\r\n]+{"hello":"🌎"}[\r\n]+--[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}--)$/
)
.reply(200, {});
const res = await request({
url,
method: 'POST',
multipart: [
{
headers: {'Content-Type': 'application/json'},
content: body,
},
],
});
scope.done();
assert.ok(res.data);
});
it('should handle multipart/related when options.multipart is set and a multiple parts', async () => {
const jsonContent = {hello: '🌎'};
const textContent = 'hello world';
const body = new Readable();
body.push(JSON.stringify(jsonContent));
body.push(null);
const scope = nock(url)
.matchHeader(
'Content-Type',
/multipart\/related; boundary=[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/
)
.post(
'/',
/^(--[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}[\r\n]+Content-Type: application\/json[\r\n\r\n]+{"hello":"🌎"}[\r\n]+--[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}[\r\n]+Content-Type: text\/plain[\r\n\r\n]+hello world[\r\n]+--[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}--)$/
)
.reply(200, {});
const res = await request({
url,
method: 'POST',
multipart: [
{
headers: {'Content-Type': 'application/json'},
content: body,
},
{
headers: {'Content-Type': 'text/plain'},
content: textContent,
},
],
});
scope.done();
assert.ok(res.data);
});
it('should redact sensitive props via the `errorRedactor` by default', async () => {
const REDACT =
'<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.';
const customURL = new URL(url);
customURL.searchParams.append('token', 'sensitive');
customURL.searchParams.append('client_secret', 'data');
customURL.searchParams.append('random', 'non-sensitive');
const config: GaxiosOptions = {
headers: {
Authentication: 'My Auth',
/**
* Ensure casing is properly handled
*/
AUTHORIZATION: 'My Auth',
'content-type': 'application/x-www-form-urlencoded',
random: 'data',
},
data: {
grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
assertion: 'somesensitivedata',
unrelated: 'data',
client_secret: 'data',
},
body: 'grant_type=somesensitivedata&assertion=somesensitivedata&client_secret=data',
};
// simulate JSON response
const responseHeaders = {
...config.headers,
'content-type': 'application/json',
};
const response = {...config.data};
const scope = nock(url)
.post('/')
.query(() => true)
.reply(404, response, responseHeaders);
const instance = new Gaxios(JSON.parse(JSON.stringify(config)));
const requestConfig: GaxiosOptions = {
url: customURL.toString(),
method: 'POST',
};
const requestConfigCopy = JSON.parse(JSON.stringify({...requestConfig}));
try {
await instance.request(requestConfig);
throw new Error('Expected a GaxiosError');
} catch (e) {
assert(e instanceof GaxiosError);
// config should not be mutated
assert.deepStrictEqual(instance.defaults, config);
assert.deepStrictEqual(requestConfig, requestConfigCopy);
assert.notStrictEqual(e.config, config);
// config redactions - headers
assert(e.config.headers);
assert.deepStrictEqual(e.config.headers, {
...config.headers, // non-redactables should be present
Authentication: REDACT,
AUTHORIZATION: REDACT,
});
// config redactions - data
assert.deepStrictEqual(e.config.data, {
...config.data, // non-redactables should be present
grant_type: REDACT,
assertion: REDACT,
client_secret: REDACT,
});
// config redactions - body
assert.deepStrictEqual(e.config.body, REDACT);
// config redactions - url
assert(e.config.url);
const resultURL = new URL(e.config.url);
assert.notDeepStrictEqual(resultURL.toString(), customURL.toString());
customURL.searchParams.set('token', REDACT);
customURL.searchParams.set('client_secret', REDACT);
assert.deepStrictEqual(resultURL.toString(), customURL.toString());
// response redactions
assert(e.response);
assert.deepStrictEqual(e.response.config, e.config);
const expectedHeaders: Headers = {
...responseHeaders, // non-redactables should be present
authentication: REDACT,
authorization: REDACT,
};
delete expectedHeaders['AUTHORIZATION'];
delete expectedHeaders['Authentication'];
assert.deepStrictEqual(e.response.headers, expectedHeaders);
assert.deepStrictEqual(e.response.data, {
...response, // non-redactables should be present
assertion: REDACT,
client_secret: REDACT,
grant_type: REDACT,
});
} finally {
scope.done();
}
});
});
describe('🍂 defaults & instances', () => {
it('should allow creating a new instance', () => {
const requestInstance = new Gaxios();
assert.strictEqual(typeof requestInstance.request, 'function');
});
it('should allow passing empty options', async () => {
const body = {hello: '🌎'};
const scope = nock(url).get('/').reply(200, body);
const gax = new Gaxios({url});
const res = await gax.request();
scope.done();
assert.deepStrictEqual(res.data, body);
});
it('should allow buffer to be posted', async () => {
const pkg = fs.readFileSync('./package.json');
const pkgJson = JSON.parse(pkg.toString('utf8'));
const scope = nock(url)
.matchHeader('content-type', 'application/dicom')
.post('/', pkgJson)
.reply(200, {});
const res = await request({
url,
method: 'POST',
data: pkg,
headers: {'content-type': 'application/dicom'},
});
scope.done();
assert.deepStrictEqual(res.data, {});
});
it('should set content-type to application/json by default, for buffer', async () => {
const pkg = fs.readFileSync('./package.json');
const pkgJson = JSON.parse(pkg.toString('utf8'));
const scope = nock(url)
.matchHeader('content-type', 'application/json')
.post('/', pkgJson)
.reply(200, {});
const res = await request({
url,
method: 'POST',
data: pkg,
});
scope.done();
assert.deepStrictEqual(res.data, {});
});
describe('mtls', () => {
class GaxiosAssertAgentCache extends Gaxios {
getAgentCache() {
return this.agentCache;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
protected async _request<T = any>(
opts: GaxiosOptions = {}
): GaxiosPromise<T> {
assert(opts.agent);
return super._request(opts);
}
}
it('uses HTTPS agent if cert and key provided, on first request', async () => {
const key = fs.readFileSync('./test/fixtures/fake.key', 'utf8');
const scope = nock(url).get('/').reply(200);
const inst = new GaxiosAssertAgentCache({
headers: {apple: 'juice'},
cert: fs.readFileSync('./test/fixtures/fake.cert', 'utf8'),
key,
});
const res = await inst.request({url, headers: {figgy: 'pudding'}});
scope.done();
assert.strictEqual(res.config.headers!.apple, 'juice');
assert.strictEqual(res.config.headers!.figgy, 'pudding');
const agentCache = inst.getAgentCache();
assert(agentCache.get(key));
});
it('uses HTTPS agent if cert and key provided, on subsequent requests', async () => {
const key = fs.readFileSync('./test/fixtures/fake.key', 'utf8');
const scope = nock(url).get('/').reply(200).get('/').reply(200);
const inst = new GaxiosAssertAgentCache({
headers: {apple: 'juice'},
cert: fs.readFileSync('./test/fixtures/fake.cert', 'utf8'),
key,
});
await inst.request({url, headers: {figgy: 'pudding'}});
await inst.request({url, headers: {figgy: 'pudding'}});
scope.done();
const agentCache = inst.getAgentCache();
assert(agentCache.get(key));
});
});
});