-
Notifications
You must be signed in to change notification settings - Fork 0
/
redish.test.js
664 lines (604 loc) · 24.2 KB
/
redish.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
const redish = require('./src/index.js')
const ObjectID = require('isomorphic-mongo-objectid')
const stringizer = require('./src/stringizer.js')
const Ajv = require('ajv')
const cmdRes = {
hDel: ['ok'],
hKeys: [[]],
hSet: ['ok'],
hGet: [{}],
multi: ['ok'],
zAdd: ['ok'],
exec: ['ok'],
hGetAll: [],
zRange: []
}
const getResponse = (cmd) => {
if (cmdRes[cmd]) {
if (cmdRes[cmd].length > 1) {
return cmdRes[cmd].pop()
} else {
return cmdRes[cmd][0]
}
} else {
return null
}
}
const mockMulti = {
exec: jest.fn(),
hSet: jest.fn(),
hDel: jest.fn(),
zAdd: jest.fn(),
del: jest.fn(),
zRem: jest.fn()
}
const mockClient = {
watch: jest.fn(),
hKeys: jest.fn(() => getResponse('hKeys')),
hGetAll: jest.fn(() => getResponse('hGetAll')),
zRange: jest.fn(() => getResponse('zRange')),
multi: jest.fn(() => mockMulti)
}
const db = redish.createDb(mockClient)
const single = db.singleton('singleton')
const schemeleton = db.singleton('schemeleton',
{
schema: {
type: 'object',
properties: {
name: { type: 'string' },
favoriteColor: { type: 'string' }
},
required: ['name']
}
})
const foo = db.collection('foo')
const audit = db.collection('audit', { enableAudit: true })
const scheme = db.collection('scheme', {
schema: {
type: 'object',
properties: {
name: { type: 'string' },
favoriteColor: { type: 'string' }
},
required: ['name']
}
})
const allTypes = {
emptyObject: {},
emptyArray: [],
emptyString: '',
null: null,
undefined,
boolean: true,
string: 'string',
BigInt: BigInt('123456789123456789'),
Symbol: Symbol.for('symbol'),
number: 100,
Date: new Date()
}
afterEach(() => {
jest.clearAllMocks()
})
describe('collection', () => {
describe('save', () => {
it('can only save truthy objects', async () => {
for (const badValue of [null, undefined, false, '', 5, -10, NaN]) {
await expect(foo.save(badValue)).rejects.toThrow('You can only save truthy objects with redish')
}
})
it('prefixes the id with the collection if set', async () => {
await foo.save({ id: 'unique' })
expect(mockMulti.hSet.mock.calls[0]).toEqual(['foo__unique', [['$.id' + ':' + stringizer.typeKeys.string, 'foo__unique']]])
})
it('generates an object id hex string if id is not set', async () => {
const result = await foo.save({})
const objectId = result.id.split('foo__')[1]
expect(ObjectID(objectId).toString()).toBe(objectId)
expect(mockMulti.hSet.mock.calls[0]).toEqual([result.id, [['$.id' + ':' + stringizer.typeKeys.string, result.id]]])
})
it('sends hDel command when keys are deleted from an existing object', async () => {
cmdRes.hKeys.push(['$.id' + ':' + stringizer.typeKeys.string, '$.foo'])
await foo.save({ id: 'id' })
expect(mockMulti.hDel.mock.calls[0]).toEqual(['foo__id', '$.foo'])
})
it('doesn\'t send hDel command when using upsert to update an existing object', async () => {
cmdRes.hKeys.push(['$.id' + ':' + stringizer.typeKeys.string, '$.foo'])
await foo.upsert({ id: 'id' })
expect(mockMulti.hDel.mock.calls.length).toEqual(0)
})
it('watches the keys if it needs to delete fields to ensure consistent updates', async () => {
cmdRes.hKeys.push(['$.id' + ':' + stringizer.typeKeys.string, '$.foo'])
await foo.save({ id: 'id' })
expect(mockClient.watch.mock.calls[0][0]).toEqual(['foo__id', 'foo'])
})
it('does not send hKeys or hDel commands if the object is new', async () => {
await foo.save({})
expect(mockClient.hKeys.mock.calls.length).toStrictEqual(0)
expect(mockMulti.hDel.mock.calls.length).toStrictEqual(0)
})
it('does not send hDel command if no keys were deleted', async () => {
cmdRes.hKeys.push(['$.id' + ':' + stringizer.typeKeys.string, '$.foo' + ':' + stringizer.typeKeys.string])
await foo.save({ id: 'id', foo: 'foo' })
expect(mockMulti.hDel.mock.calls.length).toStrictEqual(0)
})
it('adds the objects id to the collection\'s zset with a score of 0 if it\'s a new object', async () => {
const result = await foo.save({})
expect(mockMulti.zAdd.mock.calls[0]).toEqual(['foo', expect.objectContaining({ value: result.id })])
expect(mockMulti.zAdd.mock.calls[0][1].score).toBeGreaterThan(0)
})
it('saves array root objects correctly', async () => {
const result = await foo.save([5, 's'])
const objectId = result.id.split('foo__')[1]
expect(ObjectID(objectId).toString()).toBe(objectId)
expect(mockMulti.hSet.mock.calls[0])
.toEqual([
result.id, [
['$[0]' + ':' + stringizer.typeKeys.number, '5'],
['$[1]' + ':' + stringizer.typeKeys.string, 's'],
['$.id' + ':' + stringizer.typeKeys.string, result.id]
]
])
})
it('serializes types correctly', async () => {
const result = await foo.save({ ...allTypes })
expect(mockMulti.hSet.mock.calls[0])
.toEqual([
result.id, [
['$.emptyObject' + ':' + stringizer.typeKeys.emptyObject, '{}'],
['$.emptyArray' + ':' + stringizer.typeKeys.emptyArray, '[]'],
['$.emptyString' + ':' + stringizer.typeKeys.emptyString, '\'\''],
['$.null' + ':' + stringizer.typeKeys.null, 'null'],
['$.undefined' + ':' + stringizer.typeKeys.undefined, 'undefined'],
['$.boolean' + ':' + stringizer.typeKeys.boolean, 'true'],
['$.string' + ':' + stringizer.typeKeys.string, 'string'],
['$.BigInt' + ':' + stringizer.typeKeys.BigInt, '123456789123456789'],
['$.Symbol' + ':' + stringizer.typeKeys.Symbol, 'Symbol(symbol)'],
['$.number' + ':' + stringizer.typeKeys.number, '100'],
['$.Date' + ':' + stringizer.typeKeys.Date, allTypes.Date.toISOString()],
['$.id' + ':' + stringizer.typeKeys.string, result.id]
]])
})
it('serializes nested arrays correctly', async () => {
const result = await foo.save([[[[0, { foo: [[[1]]] }]]]])
expect(mockMulti.hSet.mock.calls[0])
.toEqual([
result.id, [
['$[0][0][0][0]' + ':' + stringizer.typeKeys.number, '0'],
['$[0][0][0][1].foo[0][0][0]' + ':' + stringizer.typeKeys.number, '1'],
['$.id' + ':' + stringizer.typeKeys.string, result.id]
]])
})
it('serializes nested objects correctly', async () => {
const result = await foo.save({ a: { a: { a: { a: 0, b: { b: [0, { c: 'd' }] } } } } })
expect(mockMulti.hSet.mock.calls[0])
.toEqual([
result.id, [
['$.a.a.a.a' + ':' + stringizer.typeKeys.number, '0'],
['$.a.a.a.b.b[0]' + ':' + stringizer.typeKeys.number, '0'],
['$.a.a.a.b.b[1].c' + ':' + stringizer.typeKeys.string, 'd'],
['$.id' + ':' + stringizer.typeKeys.string, result.id]
]])
})
it('sets the audit fields on new objects correctly', async () => {
const result = await audit.save({}, 'me')
expect(new Date(result.createdAt).getTime() > 0).toStrictEqual(true)
expect(result.createdBy).toStrictEqual('me')
expect(result.updatedAt).toStrictEqual(undefined)
expect(result.updatedBy).toStrictEqual(undefined)
})
it('sets the audit fields on existing objects correctly', async () => {
const theDate = (new Date().getTime() - 100000)
const result = await audit.save({ id: '1234', createdAt: theDate, createdBy: 'me' }, 'it')
expect(result.createdAt).toStrictEqual(theDate)
expect(result.createdBy).toStrictEqual('me')
expect(new Date(result.updatedAt).getTime() > 0).toStrictEqual(true)
expect(result.updatedBy).toStrictEqual('it')
})
it('validates the object using the provided schema', async () => {
await scheme.save({ id: 'unique', name: 'taco', favoriteColor: 'green' })
expect(mockMulti.hSet.mock.calls[0]).toEqual(['scheme__unique', [
['$.id' + ':' + stringizer.typeKeys.string, 'scheme__unique'],
['$.name:6', 'taco'],
['$.favoriteColor:6', 'green']
]])
})
it('throws an error with messages if the object isn\'t valid per the schema', async () => {
try {
await scheme.save({ id: 'unique', favoriteColor: 'green' })
fail('save should\'ve thrown')
} catch (e) {
expect(e.validationErrors).toEqual([{
instancePath: '',
schemaPath: '#/required',
keyword: 'required',
params: {
missingProperty: 'name'
},
message: 'must have required property \'name\''
}])
}
})
it('uses ajvOptions if passed', async () => {
const ajvOptions = db.collection('ajvOptions', {
ajvOptions: { strictNumbers: true },
schema: {
type: 'object',
properties: {
number: { type: 'number' }
},
required: ['number']
}
})
try {
await ajvOptions.save({ id: 'unique', number: '1234' })
fail('save should\'ve thrown')
} catch (e) {
expect(e.validationErrors).toEqual([{
instancePath: '/number',
schemaPath: '#/properties/number/type',
keyword: 'type',
params: {
type: 'number'
},
message: 'must be number'
}])
}
})
it('uses ajv if passed', async () => {
const ajvInst = db.collection('ajv', {
ajv: new Ajv(
{ strictNumbers: true }
),
schema: {
type: 'object',
properties: {
number: { type: 'number' }
},
required: ['number']
}
})
try {
await ajvInst.save({ id: 'unique', number: '1234' })
fail('save should\'ve thrown')
} catch (e) {
expect(e.validationErrors).toEqual([{
instancePath: '/number',
schemaPath: '#/properties/number/type',
keyword: 'type',
params: {
type: 'number'
},
message: 'must be number'
}])
}
})
})
describe('findOneById', () => {
it('should require a non empty string id is passed', async () => {
for (const badValue of [null, undefined, false, '', 0, NaN]) {
await expect(foo.findOneById(badValue)).rejects.toThrow('id must be a non-empty string')
}
})
it('deserializes types correctly', async () => {
const id = ObjectID().toString()
const origDate = allTypes.Date
const foundHash = {
['$.emptyObject' + ':' + stringizer.typeKeys.emptyObject]: '{}',
['$.emptyArray' + ':' + stringizer.typeKeys.emptyArray]: '[]',
['$.emptyString' + ':' + stringizer.typeKeys.emptyString]: '\'\'',
['$.null' + ':' + stringizer.typeKeys.null]: 'null',
['$.undefined' + ':' + stringizer.typeKeys.undefined]: 'undefined',
['$.boolean' + ':' + stringizer.typeKeys.boolean]: 'true',
['$.string' + ':' + stringizer.typeKeys.string]: 'string',
['$.BigInt' + ':' + stringizer.typeKeys.BigInt]: '123456789123456789',
['$.Symbol' + ':' + stringizer.typeKeys.Symbol]: 'Symbol(symbol)',
['$.number' + ':' + stringizer.typeKeys.number]: '100',
['$.Date' + ':' + stringizer.typeKeys.Date]: origDate.toISOString(),
['$.id' + ':' + stringizer.typeKeys.string]: id
}
cmdRes.hGetAll.push(foundHash)
const result = await foo.findOneById(id)
expect(result.emptyObject).toStrictEqual({})
expect(result.emptyArray).toStrictEqual([])
expect(result.emptyString).toStrictEqual('')
expect(result.null).toStrictEqual(null)
expect(result.undefined).toStrictEqual(undefined)
expect(result.boolean).toStrictEqual(true)
expect(result.string).toStrictEqual('string')
expect(result.BigInt).toStrictEqual(BigInt('123456789123456789'))
expect(result.Symbol).toStrictEqual(Symbol.for('symbol'))
expect(result.number).toStrictEqual(100)
expect(result.Date).toStrictEqual(origDate)
expect(result.id).toStrictEqual(id)
})
it('deserializes nested arrays correctly', async () => {
const saved = await foo.save([[[[0, { foo: [[[1]]] }]]]], { audit: false })
cmdRes.hGetAll.push({
['$[0][0][0][0]' + ':' + stringizer.typeKeys.number]: '0',
['$[0][0][0][1].foo[0][0][0]' + ':' + stringizer.typeKeys.number]: '1',
['$.id' + ':' + stringizer.typeKeys.string]: saved.id
})
const found = await foo.findOneById(saved.id)
expect(saved).toStrictEqual(found)
})
it('deserializes nested objects correctly', async () => {
const saved = await foo.save({ a: { a: { a: { a: 0, b: { b: [0, { c: 'd' }] } } } } }, { audit: false })
cmdRes.hGetAll.push({
['$.a.a.a.a' + ':' + stringizer.typeKeys.number]: '0',
['$.a.a.a.b.b[0]' + ':' + stringizer.typeKeys.number]: '0',
['$.a.a.a.b.b[1].c' + ':' + stringizer.typeKeys.string]: 'd',
['$.id' + ':' + stringizer.typeKeys.string]: saved.id
})
const found = await foo.findOneById(saved.id)
expect(saved).toStrictEqual(found)
})
it('sets the id correctly on found arrays', async () => {
const saved = await foo.save([[[[0, { foo: [[[1]]] }]]]])
cmdRes.hGetAll.push({
['$[0][0][0][0]' + ':' + stringizer.typeKeys.number]: '0',
['$[0][0][0][1].foo[0][0][0]' + ':' + stringizer.typeKeys.number]: '1',
['$.id' + ':' + stringizer.typeKeys.string]: saved.id
})
const found = await foo.findOneById(saved.id)
expect(saved.id).toBeTruthy()
expect(saved.id).toStrictEqual(found.id)
})
it('adds the key prefix to the passed id if not passed', async () => {
const foundHash = {
['$.id' + ':' + stringizer.typeKeys.string]: 'foo__12345'
}
cmdRes.hGetAll.push(foundHash)
const result = await foo.findOneById('12345')
expect(result.id).toEqual('foo__12345')
expect(mockClient.hGetAll.mock.calls[0][0]).toEqual('foo__12345')
})
it('does not add the key prefix to the passed id if passed', async () => {
const foundHash = {
['$.id' + ':' + stringizer.typeKeys.string]: 'foo__12345'
}
cmdRes.hGetAll.push(foundHash)
const result = await foo.findOneById('foo__12345')
expect(result.id).toEqual('foo__12345')
expect(mockClient.hGetAll.mock.calls[0][0]).toEqual('foo__12345')
})
})
describe('deleteById', () => {
it('calls del for the id', async () => {
await foo.deleteById('foo__123')
expect(mockMulti.del.mock.calls[0]).toEqual(['foo__123'])
})
it('adds the key prefix to the passed id if not passed', async () => {
await foo.deleteById('123')
expect(mockMulti.del.mock.calls[0]).toEqual(['foo__123'])
})
it('calls zRem if a collection key is provided', async () => {
await foo.deleteById('123')
expect(mockMulti.zRem.mock.calls[0]).toEqual(['foo', 'foo__123'])
})
})
describe('findAll', () => {
it('calls zRange with the correct start and end indexes', async () => {
await foo.findAll()
expect(mockClient.zRange.mock.calls[0].slice(0, -1)).toEqual(['foo', 0, 9])
})
it('uses the correct range for user supplied ranges', async () => {
await foo.findAll(3, 25)
expect(mockClient.zRange.mock.calls[0].slice(0, -1)).toEqual(['foo', 75, 99])
})
it('returns an empty array if no ids are found', async () => {
cmdRes.zRange.push(undefined)
const result = await foo.findAll()
expect(result).toEqual([])
})
it('calls HGETALL for each id found', async () => {
cmdRes.zRange.push(['foo__1', 'foo__2', 'foo__3', 'foo__4'])
await foo.findAll()
expect(mockClient.hGetAll.mock.calls.map(a => a[0])).toEqual(['foo__1', 'foo__2', 'foo__3', 'foo__4'])
})
})
})
describe('singleton', () => {
describe('save', () => {
it('can only save objects', async () => {
for (const badValue of [null, undefined, false, '', 5, -10, NaN, true, 'a', 0]) {
await expect(single.save(badValue)).rejects.toThrow('Only object singletons are supported')
}
})
it('sends hDel command when keys are deleted from an existing object', async () => {
cmdRes.hKeys.push(['$.id' + ':' + stringizer.typeKeys.string, '$.single'])
await single.save({ id: 'id' })
expect(mockMulti.hDel.mock.calls[0]).toEqual(['singleton', '$.single'])
})
it('doesn\'t send hDel command when using upsert to update an existing object', async () => {
cmdRes.hKeys.push(['$.id' + ':' + stringizer.typeKeys.string, '$.single'])
await single.upsert({ id: 'id' })
expect(mockMulti.hDel.mock.calls.length).toEqual(0)
})
it('watches the keys if it needs to delete fields to ensure consistent updates', async () => {
cmdRes.hKeys.push(['$.id' + ':' + stringizer.typeKeys.string, '$.single'])
await single.save({ id: 'id' })
expect(mockClient.watch.mock.calls[0][0]).toEqual(['singleton'])
})
it('does not send hDel command if no keys were deleted', async () => {
cmdRes.hKeys.push(['$.id' + ':' + stringizer.typeKeys.string, '$.single' + ':' + stringizer.typeKeys.string])
await single.save({ id: 'id', single: 'single' })
expect(mockMulti.hDel.mock.calls.length).toStrictEqual(0)
})
it('saves array root objects correctly', async () => {
await single.save([5, 's'])
expect(mockMulti.hSet.mock.calls[0])
.toEqual([
'singleton', [
['$[0]' + ':' + stringizer.typeKeys.number, '5'],
['$[1]' + ':' + stringizer.typeKeys.string, 's']
]
])
})
it('serializes types correctly', async () => {
await single.save({ ...allTypes })
expect(mockMulti.hSet.mock.calls[0])
.toEqual([
'singleton', [
['$.emptyObject' + ':' + stringizer.typeKeys.emptyObject, '{}'],
['$.emptyArray' + ':' + stringizer.typeKeys.emptyArray, '[]'],
['$.emptyString' + ':' + stringizer.typeKeys.emptyString, '\'\''],
['$.null' + ':' + stringizer.typeKeys.null, 'null'],
['$.undefined' + ':' + stringizer.typeKeys.undefined, 'undefined'],
['$.boolean' + ':' + stringizer.typeKeys.boolean, 'true'],
['$.string' + ':' + stringizer.typeKeys.string, 'string'],
['$.BigInt' + ':' + stringizer.typeKeys.BigInt, '123456789123456789'],
['$.Symbol' + ':' + stringizer.typeKeys.Symbol, 'Symbol(symbol)'],
['$.number' + ':' + stringizer.typeKeys.number, '100'],
['$.Date' + ':' + stringizer.typeKeys.Date, allTypes.Date.toISOString()]
]])
})
it('serializes nested arrays correctly', async () => {
await single.save([[[[0, { single: [[[1]]] }]]]])
expect(mockMulti.hSet.mock.calls[0])
.toEqual([
'singleton', [
['$[0][0][0][0]' + ':' + stringizer.typeKeys.number, '0'],
['$[0][0][0][1].single[0][0][0]' + ':' + stringizer.typeKeys.number, '1']
]])
})
it('serializes nested objects correctly', async () => {
await single.save({ a: { a: { a: { a: 0, b: { b: [0, { c: 'd' }] } } } } })
expect(mockMulti.hSet.mock.calls[0])
.toEqual([
'singleton', [
['$.a.a.a.a' + ':' + stringizer.typeKeys.number, '0'],
['$.a.a.a.b.b[0]' + ':' + stringizer.typeKeys.number, '0'],
['$.a.a.a.b.b[1].c' + ':' + stringizer.typeKeys.string, 'd']
]])
})
it('validates the object using the provided schema', async () => {
await schemeleton.save({ id: 'unique', name: 'taco', favoriteColor: 'green' })
expect(mockMulti.hSet.mock.calls[0]).toEqual(['schemeleton', [
['$.id' + ':' + stringizer.typeKeys.string, 'unique'],
['$.name:6', 'taco'],
['$.favoriteColor:6', 'green']
]])
})
it('throws an error with messages if the object isn\'t valid per the schema', async () => {
try {
await schemeleton.save({ id: 'unique', favoriteColor: 'green' })
fail('save should\'ve thrown')
} catch (e) {
expect(e.validationErrors).toEqual([{
instancePath: '',
schemaPath: '#/required',
keyword: 'required',
params: {
missingProperty: 'name'
},
message: 'must have required property \'name\''
}])
}
})
it('uses ajvOptions if passed', async () => {
const ajvOptions = db.singleton('ajvOptions', {
ajvOptions: { strictNumbers: true },
schema: {
type: 'object',
properties: {
number: { type: 'number' }
},
required: ['number']
}
})
try {
await ajvOptions.save({ id: 'unique', number: '1234' })
fail('save should\'ve thrown')
} catch (e) {
expect(e.validationErrors).toEqual([{
instancePath: '/number',
schemaPath: '#/properties/number/type',
keyword: 'type',
params: {
type: 'number'
},
message: 'must be number'
}])
}
})
it('uses ajv if passed', async () => {
const ajvInst = db.singleton('ajv', {
ajv: new Ajv(
{ strictNumbers: true }
),
schema: {
type: 'object',
properties: {
number: { type: 'number' }
},
required: ['number']
}
})
try {
await ajvInst.save({ id: 'unique', number: '1234' })
fail('save should\'ve thrown')
} catch (e) {
expect(e.validationErrors).toEqual([{
instancePath: '/number',
schemaPath: '#/properties/number/type',
keyword: 'type',
params: {
type: 'number'
},
message: 'must be number'
}])
}
})
})
describe('load', () => {
it('deserializes types correctly', async () => {
const origDate = allTypes.Date
const foundHash = {
['$.emptyObject' + ':' + stringizer.typeKeys.emptyObject]: '{}',
['$.emptyArray' + ':' + stringizer.typeKeys.emptyArray]: '[]',
['$.emptyString' + ':' + stringizer.typeKeys.emptyString]: '\'\'',
['$.null' + ':' + stringizer.typeKeys.null]: 'null',
['$.undefined' + ':' + stringizer.typeKeys.undefined]: 'undefined',
['$.boolean' + ':' + stringizer.typeKeys.boolean]: 'true',
['$.string' + ':' + stringizer.typeKeys.string]: 'string',
['$.BigInt' + ':' + stringizer.typeKeys.BigInt]: '123456789123456789',
['$.Symbol' + ':' + stringizer.typeKeys.Symbol]: 'Symbol(symbol)',
['$.number' + ':' + stringizer.typeKeys.number]: '100',
['$.Date' + ':' + stringizer.typeKeys.Date]: origDate.toISOString()
}
cmdRes.hGetAll.push(foundHash)
const result = await single.load()
expect(result.emptyObject).toStrictEqual({})
expect(result.emptyArray).toStrictEqual([])
expect(result.emptyString).toStrictEqual('')
expect(result.null).toStrictEqual(null)
expect(result.undefined).toStrictEqual(undefined)
expect(result.boolean).toStrictEqual(true)
expect(result.string).toStrictEqual('string')
expect(result.BigInt).toStrictEqual(BigInt('123456789123456789'))
expect(result.Symbol).toStrictEqual(Symbol.for('symbol'))
expect(result.number).toStrictEqual(100)
expect(result.Date).toStrictEqual(origDate)
})
it('deserializes nested arrays correctly', async () => {
await single.save([[[[0, { single: [[[1]]] }]]]], { audit: false })
cmdRes.hGetAll.push({
['$[0][0][0][0]' + ':' + stringizer.typeKeys.number]: '0',
['$[0][0][0][1].single[0][0][0]' + ':' + stringizer.typeKeys.number]: '1'
})
const saved = await single.load()
expect(saved).toStrictEqual([[[[0, { single: [[[1]]] }]]]])
})
it('deserializes nested objects correctly', async () => {
await single.save({ a: { a: { a: { a: 0, b: { b: [0, { c: 'd' }] } } } } }, { audit: false })
cmdRes.hGetAll.push({
['$.a.a.a.a' + ':' + stringizer.typeKeys.number]: '0',
['$.a.a.a.b.b[0]' + ':' + stringizer.typeKeys.number]: '0',
['$.a.a.a.b.b[1].c' + ':' + stringizer.typeKeys.string]: 'd'
})
const found = await single.load()
expect(found).toStrictEqual({ a: { a: { a: { a: 0, b: { b: [0, { c: 'd' }] } } } } })
})
})
})