forked from sanity-io/sanity
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.test.js
1847 lines (1597 loc) · 53.3 KB
/
client.test.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
/* eslint-disable strict */
// (Node 4 compat)
'use strict'
require('hard-rejection/register')
const test = require('tape')
const nock = require('nock')
const assign = require('xtend')
const path = require('path')
const fs = require('fs')
const validators = require('../src/validators')
const observableOf = require('rxjs').of
const {filter} = require('rxjs/operators')
const sanityClient = require('../src/sanityClient')
const SanityClient = sanityClient
const noop = () => {} // eslint-disable-line no-empty-function
const bufferFrom = (content, enc) =>
Buffer.from ? Buffer.from(content, enc) : new Buffer(content, enc) // eslint-disable-line no-buffer-constructor
const apiHost = 'api.sanity.url'
const defaultProjectId = 'bf1942'
const projectHost = (projectId) => `https://${projectId || defaultProjectId}.${apiHost}`
const clientConfig = {
apiHost: `https://${apiHost}`,
projectId: 'bf1942',
dataset: 'foo',
useCdn: false,
}
const getClient = (conf) => sanityClient(assign({}, clientConfig, conf || {}))
const fixture = (name) => path.join(__dirname, 'fixtures', name)
const ifError = (t) => (err) => {
t.ifError(err)
if (err) {
t.end()
}
}
/*****************
* BASE CLIENT *
*****************/
test('can construct client with new keyword', (t) => {
const client = new SanityClient({projectId: 'abc123'})
t.equal(client.config().projectId, 'abc123', 'constructor opts are set')
t.end()
})
test('can construct client without new keyword', (t) => {
const client = sanityClient({projectId: 'abc123'})
t.equal(client.config().projectId, 'abc123', 'constructor opts are set')
t.end()
})
test('can get and set config', (t) => {
const client = sanityClient({projectId: 'abc123'})
t.equal(client.config().projectId, 'abc123', 'constructor opts are set')
t.equal(client.config({projectId: 'def456'}), client, 'returns client on set')
t.equal(client.config().projectId, 'def456', 'new config is set')
t.end()
})
test('config getter returns a cloned object', (t) => {
const client = sanityClient({projectId: 'abc123'})
t.equal(client.config().projectId, 'abc123', 'constructor opts are set')
const config = client.config()
config.projectId = 'def456'
t.equal(client.config().projectId, 'abc123', 'returned object does not mutate client config')
t.end()
})
test('calling config() reconfigures observable API too', (t) => {
const client = sanityClient({projectId: 'abc123'})
client.config({projectId: 'def456'})
t.equal(client.observable.config().projectId, 'def456', 'Observable API gets reconfigured')
t.end()
})
test('can clone client', (t) => {
const client = sanityClient({projectId: 'abc123'})
t.equal(client.config().projectId, 'abc123', 'constructor opts are set')
const client2 = client.clone()
client2.config({projectId: 'def456'})
t.equal(client.config().projectId, 'abc123')
t.equal(client2.config().projectId, 'def456')
t.end()
})
test('throws if no projectId is set', (t) => {
t.throws(sanityClient, /projectId/)
t.end()
})
test('throws on invalid project ids', (t) => {
t.throws(() => sanityClient({projectId: '*foo*'}), /projectId.*?can only contain/i)
t.end()
})
test('throws on invalid dataset names', (t) => {
t.throws(
() => sanityClient({projectId: 'abc123', dataset: '*foo*'}),
/Datasets can only contain/i
)
t.end()
})
test('can use request() for API-relative requests', (t) => {
nock(projectHost()).get('/v1/ping').reply(200, {pong: true})
getClient()
.request({uri: '/ping'})
.then((res) => t.equal(res.pong, true))
.catch(t.ifError)
.then(t.end)
})
test('can use getUrl() to get API-relative paths', (t) => {
t.equal(getClient().getUrl('/bar/baz'), `${projectHost()}/v1/bar/baz`)
t.end()
})
test('validation', (t) => {
t.doesNotThrow(
() => validators.validateDocumentId('op', 'barfoo'),
/document ID in format/,
'does not throw on valid ID'
)
t.doesNotThrow(
() => validators.validateDocumentId('op', 'bar.foo.baz'),
/document ID in format/,
'does not throw on valid ID'
)
t.throws(
() => validators.validateDocumentId('op', 'blah#blah'),
/not a valid document ID/,
'throws on invalid ID'
)
t.end()
})
/*****************
* PROJECTS *
*****************/
test('can request list of projects', (t) => {
nock(`https://${apiHost}`)
.get('/v1/projects')
.reply(200, [{projectId: 'foo'}, {projectId: 'bar'}])
const client = sanityClient({useProjectHostname: false, apiHost: `https://${apiHost}`})
client.projects
.list()
.then((projects) => {
t.equal(projects.length, 2, 'should have two projects')
t.equal(projects[0].projectId, 'foo', 'should have project id')
})
.catch(t.ifError)
.then(t.end)
})
test('can request project by id', (t) => {
const doc = {
_id: 'projects.n1f7y',
projectId: 'n1f7y',
displayName: 'Movies Unlimited',
studioHost: 'movies',
members: [
{
id: 'someuserid',
role: 'administrator',
},
],
}
nock(`https://${apiHost}`).get('/v1/projects/n1f7y').reply(200, doc)
const client = sanityClient({useProjectHostname: false, apiHost: `https://${apiHost}`})
client.projects
.getById('n1f7y')
.then((project) => t.deepEqual(project, doc))
.catch(t.ifError)
.then(t.end)
})
/*****************
* DATASETS *
*****************/
test('throws when trying to create dataset with invalid name', (t) => {
t.throws(() => getClient().datasets.create('*foo*'), /Datasets can only contain/i)
t.end()
})
test('throws when trying to delete dataset with invalid name', (t) => {
t.throws(() => getClient().datasets.delete('*foo*'), /Datasets can only contain/i)
t.end()
})
test('can create dataset', (t) => {
nock(projectHost()).put('/v1/datasets/bar').reply(200)
getClient().datasets.create('bar').catch(t.ifError).then(t.end)
})
test('can delete dataset', (t) => {
nock(projectHost()).delete('/v1/datasets/bar').reply(200)
getClient().datasets.delete('bar').catch(t.ifError).then(t.end)
})
test('can list datasets', (t) => {
nock(projectHost()).get('/v1/datasets').reply(200, ['foo', 'bar'])
getClient()
.datasets.list()
.then((sets) => {
t.deepEqual(sets, ['foo', 'bar'])
})
.catch(t.ifError)
.then(t.end)
})
/*****************
* DATA *
*****************/
test('can query for documents', (t) => {
const query = 'beerfiesta.beer[.title == $beerName]'
const params = {beerName: 'Headroom Double IPA'}
const qs =
'beerfiesta.beer%5B.title%20%3D%3D%20%24beerName%5D&%24beerName=%22Headroom%20Double%20IPA%22'
nock(projectHost())
.get(`/v1/data/query/foo?query=${qs}`)
.reply(200, {
ms: 123,
q: query,
result: [{_id: 'njgNkngskjg', rating: 5}],
})
getClient()
.fetch(query, params)
.then((res) => {
t.equal(res.length, 1, 'length should match')
t.equal(res[0].rating, 5, 'data should match')
})
.catch(t.ifError)
.then(t.end)
})
test('can query for documents and return full response', (t) => {
const query = 'beerfiesta.beer[.title == $beerName]'
const params = {beerName: 'Headroom Double IPA'}
const qs =
'beerfiesta.beer%5B.title%20%3D%3D%20%24beerName%5D&%24beerName=%22Headroom%20Double%20IPA%22'
nock(projectHost())
.get(`/v1/data/query/foo?query=${qs}`)
.reply(200, {
ms: 123,
q: query,
result: [{_id: 'njgNkngskjg', rating: 5}],
})
getClient()
.fetch(query, params, {filterResponse: false})
.then((res) => {
t.equal(res.ms, 123, 'should include timing info')
t.equal(res.q, query, 'should include query')
t.equal(res.result.length, 1, 'length should match')
t.equal(res.result[0].rating, 5, 'data should match')
})
.catch(t.ifError)
.then(t.end)
})
test('handles api errors gracefully', (t) => {
const response = {
statusCode: 403,
error: 'Forbidden',
message: 'You are not allowed to access this resource',
}
nock(projectHost()).get('/v1/data/query/foo?query=area51').times(5).reply(403, response)
getClient()
.fetch('area51')
.then((res) => {
t.fail('Resolve handler should not be called on failure')
t.end()
})
.catch((err) => {
t.ok(err instanceof Error, 'should be error')
t.ok(err.message.includes(response.error), 'should contain error code')
t.ok(err.message.includes(response.message), 'should contain error message')
t.ok(err.responseBody.includes(response.message), 'responseBody should be populated')
t.end()
})
})
test('handles db errors gracefully', (t) => {
const response = {
error: {
column: 13,
line: 'foo.bar.baz 12#[{',
lineNumber: 1,
description: 'Unable to parse entire expression',
query: 'foo.bar.baz 12#[{',
type: 'gqlParseError',
},
}
nock(projectHost())
.get('/v1/data/query/foo?query=foo.bar.baz%20%2012%23%5B%7B')
.reply(400, response)
getClient()
.fetch('foo.bar.baz 12#[{')
.then((res) => {
t.fail('Resolve handler should not be called on failure')
t.end()
})
.catch((err) => {
t.ok(err instanceof Error, 'should be error')
t.ok(err.message.includes(response.error.description), 'should contain error description')
t.equal(err.details.column, response.error.column, 'error should have details object')
t.equal(err.details.line, response.error.line, 'error should have details object')
t.end()
})
})
test('can query for single document', (t) => {
nock(projectHost())
.get('/v1/data/doc/foo/abc123')
.reply(200, {
ms: 123,
documents: [{_id: 'abc123', mood: 'lax'}],
})
getClient()
.getDocument('abc123')
.then((res) => {
t.equal(res.mood, 'lax', 'data should match')
})
.catch(t.ifError)
.then(t.end)
})
test('can query for multiple documents', (t) => {
nock(projectHost())
.get('/v1/data/doc/foo/abc123,abc321')
.reply(200, {
ms: 123,
documents: [
{_id: 'abc123', mood: 'lax'},
{_id: 'abc321', mood: 'tense'},
],
})
getClient()
.getDocuments(['abc123', 'abc321'])
.then(([abc123, abc321]) => {
t.equal(abc123.mood, 'lax', 'data should match')
t.equal(abc321.mood, 'tense', 'data should match')
})
.catch(t.ifError)
.then(t.end)
})
test('preserves the position of requested documents', (t) => {
nock(projectHost())
.get('/v1/data/doc/foo/abc123,abc321,abc456')
.reply(200, {
ms: 123,
documents: [
{_id: 'abc456', mood: 'neutral'},
{_id: 'abc321', mood: 'tense'},
],
})
getClient()
.getDocuments(['abc123', 'abc321', 'abc456'])
.then(([abc123, abc321, abc456]) => {
t.equal(abc123, null, 'first item should be null')
t.equal(abc321.mood, 'tense', 'data should match')
t.equal(abc456.mood, 'neutral', 'data should match')
})
.catch(t.ifError)
.then(t.end)
})
test('gives http statuscode as error if no body is present on errors', (t) => {
nock(projectHost()).get('/v1/data/doc/foo/abc123').reply(400)
getClient()
.getDocument('abc123')
.then((res) => {
t.fail('Resolve handler should not be called on failure')
t.end()
})
.catch((err) => {
t.ok(err instanceof Error, 'should be error')
t.ok(err.message.includes('HTTP 400'), 'should contain status code')
t.end()
})
})
test('populates response body on errors', (t) => {
nock(projectHost()).get('/v1/data/doc/foo/abc123').times(5).reply(400, 'Some Weird Error')
getClient()
.getDocument('abc123')
.then((res) => {
t.fail('Resolve handler should not be called on failure')
t.end()
})
.catch((err) => {
t.ok(err instanceof Error, 'should be error')
t.ok(err.message.includes('HTTP 400'), 'should contain status code')
t.ok((err.responseBody || '').includes('Some Weird Error'), 'body populated')
t.end()
})
})
test('throws if trying to perform data request without dataset', (t) => {
t.throws(
() => sanityClient({projectId: 'foo'}).fetch('blah'),
Error,
/dataset.*?must be provided/
)
t.end()
})
test('can create documents', (t) => {
const doc = {_id: 'abc123', name: 'Raptor'}
nock(projectHost())
.post('/v1/data/mutate/foo?returnIds=true&returnDocuments=true&visibility=sync', {
mutations: [{create: doc}],
})
.reply(200, {
transactionId: 'abc123',
results: [
{
document: {_id: 'abc123', _createdAt: '2016-10-24T08:09:32.997Z', name: 'Raptor'},
operation: 'create',
},
],
})
getClient()
.create(doc)
.then((res) => {
t.equal(res._id, doc._id, 'document id returned')
t.ok(res._createdAt, 'server-generated attributes are included')
})
.catch(t.ifError)
.then(t.end)
})
test('can create documents without specifying ID', (t) => {
const doc = {name: 'Raptor'}
const expectedBody = {mutations: [{create: Object.assign({}, doc)}]}
nock(projectHost())
.post('/v1/data/mutate/foo?returnIds=true&returnDocuments=true&visibility=sync', expectedBody)
.reply(200, {
transactionId: '123abc',
results: [
{
id: 'abc456',
document: {_id: 'abc456', name: 'Raptor'},
},
],
})
getClient()
.create(doc)
.then((res) => {
t.equal(res._id, 'abc456', 'document id returned')
})
.catch(t.ifError)
.then(t.end)
})
test('can tell create() not to return documents', (t) => {
const doc = {_id: 'abc123', name: 'Raptor'}
nock(projectHost())
.post('/v1/data/mutate/foo?returnIds=true&visibility=sync', {mutations: [{create: doc}]})
.reply(200, {transactionId: 'abc123', results: [{id: 'abc123', operation: 'create'}]})
getClient()
.create(doc, {returnDocuments: false})
.then((res) => {
t.equal(res.transactionId, 'abc123', 'returns transaction ID')
t.equal(res.documentId, 'abc123', 'returns document id')
})
.catch(t.ifError)
.then(t.end)
})
test('can tell create() to use non-default visibility mode', (t) => {
const doc = {_id: 'abc123', name: 'Raptor'}
nock(projectHost())
.post('/v1/data/mutate/foo?returnIds=true&returnDocuments=true&visibility=async', {
mutations: [{create: doc}],
})
.reply(200, {
transactionId: 'abc123',
results: [{id: 'abc123', document: doc, operation: 'create'}],
})
getClient()
.create(doc, {visibility: 'async'})
.then((res) => {
t.equal(res._id, 'abc123', 'document id returned')
})
.catch(t.ifError)
.then(t.end)
})
test('createIfNotExists() sends correct mutation', (t) => {
const doc = {_id: 'abc123', name: 'Raptor'}
const expectedBody = {mutations: [{createIfNotExists: doc}]}
nock(projectHost())
.post('/v1/data/mutate/foo?returnIds=true&returnDocuments=true&visibility=sync', expectedBody)
.reply(200, {
transactionId: '123abc',
results: [{id: 'abc123', document: doc, operation: 'create'}],
})
getClient()
.createIfNotExists(doc)
.catch(t.ifError)
.then(() => t.end())
})
test('can tell createIfNotExists() not to return documents', (t) => {
const doc = {_id: 'abc123', name: 'Raptor'}
const expectedBody = {mutations: [{createIfNotExists: doc}]}
nock(projectHost())
.post('/v1/data/mutate/foo?returnIds=true&visibility=sync', expectedBody)
.reply(200, {transactionId: 'abc123', results: [{id: 'abc123', operation: 'create'}]})
getClient()
.createIfNotExists(doc, {returnDocuments: false})
.then((res) => {
t.equal(res.transactionId, 'abc123', 'returns transaction ID')
t.equal(res.documentId, 'abc123', 'returns document id')
})
.catch(t.ifError)
.then(t.end)
})
test('createOrReplace() sends correct mutation', (t) => {
const doc = {_id: 'abc123', name: 'Raptor'}
const expectedBody = {mutations: [{createOrReplace: doc}]}
nock(projectHost())
.post('/v1/data/mutate/foo?returnIds=true&returnDocuments=true&visibility=sync', expectedBody)
.reply(200, {transactionId: '123abc', results: [{id: 'abc123', operation: 'create'}]})
getClient().createOrReplace(doc).catch(t.ifError).then(t.end)
})
test('can tell createOrReplace() not to return documents', (t) => {
const doc = {_id: 'abc123', name: 'Raptor'}
const expectedBody = {mutations: [{createOrReplace: doc}]}
nock(projectHost())
.post('/v1/data/mutate/foo?returnIds=true&visibility=sync', expectedBody)
.reply(200, {transactionId: 'abc123', results: [{id: 'abc123', operation: 'create'}]})
getClient()
.createOrReplace(doc, {returnDocuments: false})
.then((res) => {
t.equal(res.transactionId, 'abc123', 'returns transaction ID')
t.equal(res.documentId, 'abc123', 'returns document id')
})
.catch(t.ifError)
.then(t.end)
})
test('delete() sends correct mutation', (t) => {
const expectedBody = {mutations: [{delete: {id: 'abc123'}}]}
nock(projectHost())
.post('/v1/data/mutate/foo?returnIds=true&returnDocuments=true&visibility=sync', expectedBody)
.reply(200, {transactionId: 'abc123', results: [{id: 'abc123', operation: 'delete'}]})
getClient()
.delete('abc123')
.catch(t.ifError)
.then(() => t.end())
})
test('delete() can use query', (t) => {
const expectedBody = {mutations: [{delete: {query: 'foo.sometype'}}]}
nock(projectHost())
.post('/v1/data/mutate/foo?returnIds=true&returnDocuments=true&visibility=sync', expectedBody)
.reply(200, {transactionId: 'abc123'})
getClient()
.delete({query: 'foo.sometype'})
.catch(t.ifError)
.then(() => t.end())
})
test('delete() can be told not to return documents', (t) => {
const expectedBody = {mutations: [{delete: {id: 'abc123'}}]}
nock(projectHost())
.post('/v1/data/mutate/foo?returnIds=true&visibility=sync', expectedBody)
.reply(200, {transactionId: 'abc123', results: [{id: 'abc123', operation: 'delete'}]})
getClient()
.delete('abc123', {returnDocuments: false})
.catch(t.ifError)
.then(() => t.end())
})
test('mutate() accepts multiple mutations', (t) => {
const docs = [
{
_id: 'movies.raiders-of-the-lost-ark',
title: 'Raiders of the Lost Ark',
year: 1981,
},
{
_id: 'movies.the-phantom-menace',
title: 'Star Wars: Episode I - The Phantom Menace',
year: 1999,
},
]
const mutations = [{create: docs[0]}, {delete: {id: 'movies.the-phantom-menace'}}]
nock(projectHost())
.post('/v1/data/mutate/foo?returnIds=true&returnDocuments=true&visibility=sync', {mutations})
.reply(200, {
transactionId: 'foo',
results: [
{id: 'movies.raiders-of-the-lost-ark', operation: 'create', document: docs[0]},
{id: 'movies.the-phantom-menace', operation: 'delete', document: docs[1]},
],
})
getClient()
.mutate(mutations)
.catch(t.ifError)
.then(() => t.end())
})
test('uses GET for queries below limit', (t) => {
// Please dont ever do this. Just... don't.
const clause = []
const qParams = {}
const params = {}
for (let i = 1950; i <= 2016; i++) {
clause.push(`title == $beerName${i}`)
params[`beerName${i}`] = `some beer ${i}`
qParams[`$beerName${i}`] = JSON.stringify(`some beer ${i}`)
}
// Again, just... don't do this.
const query = `*[is "beer" && (${clause.join(' || ')})]`
nock(projectHost())
.get('/v1/data/query/foo')
.query(Object.assign({query}, qParams))
.reply(200, {
ms: 123,
q: query,
result: [{_id: 'njgNkngskjg', rating: 5}],
})
getClient()
.fetch(query, params)
.then((res) => {
t.equal(res.length, 1, 'length should match')
t.equal(res[0].rating, 5, 'data should match')
})
.catch(t.ifError)
.then(t.end)
})
test('uses POST for long queries', (t) => {
// Please dont ever do this. Just... don't.
const clause = []
const params = {}
for (let i = 1866; i <= 2016; i++) {
clause.push(`title == $beerName${i}`)
params[`beerName${i}`] = `some beer ${i}`
}
// Again, just... don't do this.
const query = `*[is "beer" && (${clause.join(' || ')})]`
nock(projectHost())
.filteringRequestBody(/.*/, '*')
.post('/v1/data/query/foo', '*')
.reply(200, {
ms: 123,
q: query,
result: [{_id: 'njgNkngskjg', rating: 5}],
})
getClient()
.fetch(query, params)
.then((res) => {
t.equal(res.length, 1, 'length should match')
t.equal(res[0].rating, 5, 'data should match')
})
.catch(t.ifError)
.then(t.end)
})
/*****************
* PATCH OPS *
*****************/
test('can build and serialize a patch of operations', (t) => {
const patch = getClient().patch('abc123').inc({count: 1}).set({brownEyes: true}).serialize()
t.deepEqual(patch, {id: 'abc123', inc: {count: 1}, set: {brownEyes: true}})
t.end()
})
test('patch() can take an array of IDs', (t) => {
const patch = getClient().patch(['abc123', 'foo.456']).inc({count: 1}).serialize()
t.deepEqual(patch, {id: ['abc123', 'foo.456'], inc: {count: 1}})
t.end()
})
test('patch() can take a query', (t) => {
const patch = getClient().patch({query: 'beerfiesta.beer'}).inc({count: 1}).serialize()
t.deepEqual(patch, {query: 'beerfiesta.beer', inc: {count: 1}})
t.end()
})
test('merge() patch can be applied multiple times', (t) => {
const patch = getClient()
.patch('abc123')
.merge({count: 1, foo: 'bar'})
.merge({count: 2, bar: 'foo'})
.serialize()
t.deepEqual(patch, {id: 'abc123', merge: {count: 2, foo: 'bar', bar: 'foo'}})
t.end()
})
test('setIfMissing() patch can be applied multiple times', (t) => {
const patch = getClient()
.patch('abc123')
.setIfMissing({count: 1, foo: 'bar'})
.setIfMissing({count: 2, bar: 'foo'})
.serialize()
t.deepEqual(patch, {id: 'abc123', setIfMissing: {count: 2, foo: 'bar', bar: 'foo'}})
t.end()
})
test('only last replace() patch call gets applied', (t) => {
const patch = getClient()
.patch('abc123')
.replace({count: 1, foo: 'bar'})
.replace({count: 2, bar: 'foo'})
.serialize()
t.deepEqual(patch, {id: 'abc123', set: {$: {count: 2, bar: 'foo'}}})
t.end()
})
test('can apply inc() and dec()', (t) => {
const patch = getClient()
.patch('abc123')
.inc({count: 1}) // One step forward
.dec({count: 2}) // Two steps back
.serialize()
t.deepEqual(patch, {id: 'abc123', inc: {count: 1}, dec: {count: 2}})
t.end()
})
test('can apply unset()', (t) => {
const patch = getClient()
.patch('abc123')
.inc({count: 1})
.unset(['bitter', 'enchilada'])
.serialize()
t.deepEqual(patch, {id: 'abc123', inc: {count: 1}, unset: ['bitter', 'enchilada']})
t.end()
})
test('throws if non-array is passed to unset()', (t) => {
t.throws(() => getClient().patch('abc123').unset('bitter').serialize(), /non-array given/)
t.end()
})
test('can apply insert()', (t) => {
const patch = getClient()
.patch('abc123')
.inc({count: 1})
.insert('after', 'tags[-1]', ['hotsauce'])
.serialize()
t.deepEqual(patch, {
id: 'abc123',
inc: {count: 1},
insert: {after: 'tags[-1]', items: ['hotsauce']},
})
t.end()
})
test('throws on invalid insert()', (t) => {
t.throws(
() => getClient().patch('abc123').insert('bitter', 'sel', ['raf']),
/one of: "before", "after", "replace"/
)
t.throws(() => getClient().patch('abc123').insert('before', 123, ['raf']), /must be a string/)
t.throws(() => getClient().patch('abc123').insert('before', 'prop', 'blah'), /must be an array/)
t.end()
})
test('can apply append()', (t) => {
const patch = getClient().patch('abc123').inc({count: 1}).append('tags', ['sriracha']).serialize()
t.deepEqual(patch, {
id: 'abc123',
inc: {count: 1},
insert: {after: 'tags[-1]', items: ['sriracha']},
})
t.end()
})
test('can apply prepend()', (t) => {
const patch = getClient()
.patch('abc123')
.inc({count: 1})
.prepend('tags', ['sriracha', 'hotsauce'])
.serialize()
t.deepEqual(patch, {
id: 'abc123',
inc: {count: 1},
insert: {before: 'tags[0]', items: ['sriracha', 'hotsauce']},
})
t.end()
})
test('can apply splice()', (t) => {
const patch = () => getClient().patch('abc123')
const replaceFirst = patch().splice('tags', 0, 1, ['foo']).serialize()
const insertInMiddle = patch().splice('tags', 5, 0, ['foo']).serialize()
const deleteLast = patch().splice('tags', -1, 1).serialize()
const deleteAllFromIndex = patch().splice('tags', 3, -1).serialize()
const allFromIndexDefault = patch().splice('tags', 3).serialize()
const negativeDelete = patch().splice('tags', -2, -2, ['foo']).serialize()
t.deepEqual(replaceFirst.insert, {replace: 'tags[0:1]', items: ['foo']})
t.deepEqual(insertInMiddle.insert, {replace: 'tags[5:5]', items: ['foo']})
t.deepEqual(deleteLast.insert, {replace: 'tags[-2:]', items: []})
t.deepEqual(deleteAllFromIndex.insert, {replace: 'tags[3:-1]', items: []})
t.deepEqual(allFromIndexDefault.insert, {replace: 'tags[3:-1]', items: []})
t.deepEqual(negativeDelete, patch().splice('tags', -2, 0, ['foo']).serialize())
t.end()
})
test('serializing invalid selectors throws', (t) => {
t.throws(() => getClient().patch(123).serialize(), /unknown selection/i)
t.end()
})
test('can apply diffMatchPatch()', (t) => {
const patch = getClient()
.patch('abc123')
.inc({count: 1})
.diffMatchPatch({description: '@@ -1,13 +1,12 @@\n The \n-rabid\n+nice\n dog\n'})
.serialize()
t.deepEqual(patch, {
id: 'abc123',
inc: {count: 1},
diffMatchPatch: {description: '@@ -1,13 +1,12 @@\n The \n-rabid\n+nice\n dog\n'},
})
t.end()
})
test('all patch methods throw on non-objects being passed as argument', (t) => {
const patch = getClient().patch('abc123')
t.throws(() => patch.merge([]), /merge\(\) takes an object of properties/, 'merge throws')
t.throws(() => patch.set(null), /set\(\) takes an object of properties/, 'set throws')
t.throws(
() => patch.setIfMissing('foo'),
/setIfMissing\(\) takes an object of properties/,
'setIfMissing throws'
)
t.throws(
() => patch.replace('foo'),
/replace\(\) takes an object of properties/,
'replace throws'
)
t.throws(() => patch.inc('foo'), /inc\(\) takes an object of properties/, 'inc throws')
t.throws(() => patch.dec('foo'), /dec\(\) takes an object of properties/, 'dec throws')
t.throws(
() => patch.diffMatchPatch('foo'),
/diffMatchPatch\(\) takes an object of properties/,
'diffMatchPatch throws'
)
t.end()
})
test('executes patch when commit() is called', (t) => {
const expectedPatch = {patch: {id: 'abc123', inc: {count: 1}, set: {visited: true}}}
nock(projectHost())
.post('/v1/data/mutate/foo?returnIds=true&visibility=sync', {mutations: [expectedPatch]})
.reply(200, {transactionId: 'blatti'})
getClient()
.patch('abc123')
.inc({count: 1})
.set({visited: true})
.commit({returnDocuments: false})
.then((res) => {
t.equal(res.transactionId, 'blatti', 'applies given patch')
})
.catch(t.ifError)
.then(t.end)
})
test('executes patch with given token override commit() is called', (t) => {
const expectedPatch = {patch: {id: 'abc123', inc: {count: 1}, set: {visited: true}}}
nock(projectHost(), {reqheaders: {Authorization: 'Bearer abc123'}})
.post('/v1/data/mutate/foo?returnIds=true&visibility=sync', {mutations: [expectedPatch]})
.reply(200, {transactionId: 'blatti'})
getClient()
.patch('abc123')
.inc({count: 1})
.set({visited: true})
.commit({returnDocuments: false, token: 'abc123'})
.then((res) => {
t.equal(res.transactionId, 'blatti', 'applies given patch')
})
.catch(t.ifError)
.then(t.end)
})
test('returns patched document by default', (t) => {
const expectedPatch = {patch: {id: 'abc123', inc: {count: 1}, set: {visited: true}}}
const expectedBody = {mutations: [expectedPatch]}
nock(projectHost())
.post('/v1/data/mutate/foo?returnIds=true&returnDocuments=true&visibility=sync', expectedBody)
.reply(200, {
transactionId: 'blatti',
results: [
{
id: 'abc123',
operation: 'update',
document: {
_id: 'abc123',
_createdAt: '2016-10-24T08:09:32.997Z',
count: 2,
visited: true,
},
},
],
})
getClient()
.patch('abc123')
.inc({count: 1})
.set({visited: true})
.commit()
.then((res) => {
t.equal(res._id, 'abc123', 'returns patched document')
})
.catch(t.ifError)
.then(t.end)
})
test('commit() returns promise', (t) => {
const expectedPatch = {patch: {id: 'abc123', inc: {count: 1}, set: {visited: true}}}
const expectedBody = {mutations: [expectedPatch]}
nock(projectHost())
.post('/v1/data/mutate/foo?returnIds=true&returnDocuments=true&visibility=sync', expectedBody)
.reply(400)
getClient()
.patch('abc123')
.inc({count: 1})
.set({visited: true})
.commit()
.catch((err) => {
t.ok(err instanceof Error, 'should call applied error handler')
t.end()
})
})
test('each patch operation returns same patch', (t) => {
const patch = getClient().patch('abc123')
const inc = patch.inc({count: 1})
const dec = patch.dec({count: 1})
const combined = inc.dec({count: 1})