-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
805 lines (634 loc) · 26 KB
/
index.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
'use strict';
const debug = require('debug')('code'),
Redis = require('ioredis'),
crypto = require('crypto'),
clone = require('clone');
require('console.table');
function RigidDB(prefix, revision, redisOpts, redisErrorHandler) {
if (!prefix || !onlyLetters(prefix)) {
throw('Invalid prefix.');
}
if (!Number.isInteger(revision)) {
throw('Invalid revision.');
}
this.prefix = prefix;
this.revision = revision;
this.schemaLoading = true;
this.invalidSavedSchema = false;
this.schema = null;
redisOpts = redisOpts || {};
this.client = new Redis({
port: redisOpts.port,
host: redisOpts.host,
password: redisOpts.password,
db: redisOpts.db,
retryStrategy: redisOpts.retryStrategy
});
if (redisErrorHandler) {
this.client.on('error', redisErrorHandler);
}
this.schemaPromise = this.client.get(`${this._keyPrefix}:_schema`).then(result => {
this.schemaLoading = false;
if (result) {
try {
this.srcSchema = JSON.parse(result);
} catch(e) {
this.invalidSavedSchema = true;
return;
}
let ret = this._normalizeAndVerifySchema(this.srcSchema);
if (ret.err) {
this.invalidSavedSchema = true;
} else {
this.schema = ret.schema;
}
}
});
}
RigidDB.prototype.quit = function() {
return this.client.quit();
};
RigidDB.prototype.setSchema = function(schema) {
return this._whenSchemaLoaded(() => this._setSchema(schema));
};
RigidDB.prototype.getSchema = function() {
return this._whenSchemaLoaded(() => this._getSchema());
};
RigidDB.prototype.create = function(collection, attrs) {
return this._execSingle(this._create, 'create', collection, attrs);
};
RigidDB.prototype.update = function(collection, id, attrs) {
return this._execSingle(this._update, 'update', collection, id, attrs);
};
RigidDB.prototype.delete = function(collection, id) {
return this._execSingle(this._delete, 'delete', collection, id);
};
RigidDB.prototype.get = function(collection, id) {
return this._execSingle(this._get, 'get', collection, id);
};
RigidDB.prototype.exists = function(collection, id) {
return this._execSingle(this._exists, 'exists', collection, id);
};
RigidDB.prototype.list = function(collection) {
return this._execSingle(this._list, 'list', collection);
};
RigidDB.prototype.size = function(collection) {
return this._execSingle(this._size, 'size', collection);
};
RigidDB.prototype.currentId = function(collection) {
return this._execSingle(this._currentId, 'currentId', collection);
};
RigidDB.prototype.multi = function(cb) {
return this._whenSchemaLoaded(() => this._execMultiNow(cb));
};
RigidDB.prototype.find = function(collection, searchAttrs) {
return this._execSingle(this._find, 'find', collection, searchAttrs);
};
// Print is for debugging, doesn't scale currently
RigidDB.prototype.debugPrint = function(collection) {
let data = [];
return this.client.zrange(`${this._keyPrefix}:${collection}:ids`, 0, -1).then(ids =>
ids.reduce((sequence, id) => sequence.then(() =>
this.client.hgetall(`${this._keyPrefix}:${collection}:${id}`).then(result => {
result = this._processRedisAttrsForPrinting(collection, result);
result.id = id;
data.push(result);
})), Promise.resolve())).then(() => {
console.table(data); // eslint-disable-line no-console
});
};
RigidDB.prototype._setSchema = function(schema) {
let srcSchemaJSON = '';
if (this.schema) {
return Promise.resolve({ val: false, reason: 'Schema already exists', method: 'setSchema'});
}
try {
srcSchemaJSON = JSON.stringify(schema);
} catch(e) {
return Promise.resolve({ val: false, reason: 'Invalid schema.', method: 'setSchema' });
}
let ret = this._normalizeAndVerifySchema(schema);
if (ret.err) {
return Promise.resolve({ val: false, reason: ret.err, method: 'setSchema' });
}
this.srcSchema = schema;
this.schema = ret.schema;
return this.client.set(`${this._keyPrefix}:_schema`, srcSchemaJSON)
.then(() => ({ val: true }));
};
RigidDB.prototype._normalizeAndVerifySchema = function(schema) {
schema = clone(schema);
if (typeof(schema) !== 'object' || schema === null) {
return { err: 'Invalid schema.' };
}
let collections = Object.keys(schema);
if (collections.length === 0) {
return { err: 'At least one collection must be defined.' };
}
for (let collectionName of collections) {
let definition = schema[collectionName].definition;
let indices = schema[collectionName].indices || {};
if (!definition) {
return { err: 'Definition missing.' };
}
let fieldNames = Object.keys(definition);
for (let fieldName of fieldNames) {
if (!onlyLettersNumbersDashes(fieldName)) {
return { err: `Invalid field name (letters, numbers, and dashes allowed): '${fieldName}'` };
}
if (typeof(definition[fieldName]) === 'string') {
definition[fieldName] = { type: definition[fieldName], allowNull: true };
} else if (definition[fieldName].allowNull === undefined) {
definition[fieldName].allowNull = true;
}
let type = definition[fieldName];
if (!type || !type.type) {
return { err: `Type definition missing.` };
}
if (!/^(string|int|boolean|date|timestamp)$/.test(type.type)) {
return { err: `Invalid type: '${type.type}'` };
}
type.allowMulti = !!type.allowMulti;
}
for (let indexName in indices) {
let index = indices[indexName];
if (!(index.uniq === true || index.uniq === false)) {
return { err: 'Invalid or missing index unique definition' };
}
if (!index.fields || !(index.fields instanceof Array) || index.fields.length == 0) {
return { err: 'Invalid or missing index fields definition' };
}
let normalizedIndexFields = [];
for (let field of index.fields) {
if (typeof(field) === 'string') {
field = { name: field, caseInsensitive: false };
}
if (fieldNames.indexOf(field.name) === -1) {
return { err: `Invalid index field name: '${field.name}'` };
}
for (let indexFieldProp of Object.keys(field)) {
if (indexFieldProp !== 'name' && indexFieldProp !== 'caseInsensitive') {
return { err: `Invalid index field property: '${indexFieldProp}'` };
}
}
field.caseInsensitive = !!field.caseInsensitive;
normalizedIndexFields.push(field);
}
index.fields = normalizedIndexFields;
}
}
return { err: false, schema: schema };
};
RigidDB.prototype._getSchema = function() {
return Promise.resolve(this.schema ? { val: { revision: 1, schema: this.srcSchema } } :
{ val: false, err: 'schemaMissing', method: 'getSchema'});
};
RigidDB.prototype._execMultiNow = function(cb) {
let ctx = newContext();
if (this.invalidSavedSchema) {
ctx.error = { method: 'multi', err: 'badSavedSchema' };
} else if (!this.schema) {
ctx.error = { method: 'multi', err: 'schemaMissing' };
} else {
const execute = (op, methodName, args) => {
let collection = args[0];
if (!this.schema[collection]) {
ctx.error = { method: methodName, err: 'unknownCollection' };
}
if (!ctx.error) {
this[op].apply(this, [ ctx ].concat(args));
}
};
let api = {
create: (collection, attrs) => execute('_create', 'create', [ collection, attrs ]),
update: (collection, id, attrs) => execute('_update', 'update', [ collection, id, attrs ]),
delete: (collection, id) => execute('_delete', 'delete', [ collection, id ]),
get: (collection, id) => execute('_get', 'get', [ collection, id ]),
exists: (collection, id) => execute('_exists', 'exists', [ collection, id ])
};
cb(api);
}
return this._exec(ctx);
};
RigidDB.prototype._execSingle = function() {
let args = Array.prototype.slice.call(arguments);
let method = args.shift();
let methodName = args.shift();
let ctx = newContext();
return this._whenSchemaLoaded(() => this._execSingleNow(ctx, method, methodName, args));
};
RigidDB.prototype._execSingleNow = function(ctx, method, methodName, args) {
let collection = args[0];
if (this.invalidSavedSchema) {
ctx.error = { method: methodName, err: 'badSavedSchema' };
} else if (!this.schema) {
ctx.error = { method: methodName, err: 'schemaMissing' };
} else if (!this.schema[collection]) {
ctx.error = { method: methodName, err: 'unknownCollection' };
}
if (!ctx.error) {
args.unshift(ctx);
method.apply(this, args);
}
return this._exec(ctx);
};
RigidDB.prototype._exec = function(ctx) {
if (ctx.error) {
return Promise.resolve({ val: false, err: ctx.error.err, method: ctx.error.method });
}
let code = `${utilityFuncs()}\n local ret = { 'none', 'noError' }\n ${ctx.script}\n return ret`;
let sha1 = crypto.createHash('sha1').update(code).digest('hex');
let evalParams = [ sha1, 0 ].concat(ctx.params);
debug(`PARAMETERS : ${ctx.params}`);
debug(code);
const decodeResult = ret => {
let method = ret[0];
let err = ret[1];
let val = ret[2];
if (err != 'noError') {
if (method === 'create' || method == 'update') {
return { val: false, err: err, method: method, indices: val || [] };
} else {
return { val: false, err: err, method: method };
}
}
if (method === 'get') {
val = this._processRedisGetReturnValue(ret[3], val);
} else if (method === 'exists') {
val = !!val; // Lua returns 0 (not found) or 1 (found)
} else if (method === 'currentId') {
val = parseInt(val);
} else if (method === 'list' || method === 'find') {
val = val.map(item => parseInt(item));
} else if (method === 'delete' || method === 'none') {
val = true;
}
return { val: val };
};
const redisEval = (failure) => this.client.evalsha(evalParams).then(decodeResult, failure);
// Try to evaluate by SHA first. If that fails, load the script. If it still fails, give up and
// do nothing.
return redisEval(() => this.client.script('load', code).then(redisEval));
};
RigidDB.prototype._whenSchemaLoaded = function(cb) {
return this.schemaLoading ? this.schemaPromise.then(cb) : cb();
};
RigidDB.prototype._create = function(ctx, collection, attrs) {
let redisAttrs = this._normalizeRedisAttrs(collection, attrs);
if (redisAttrs.err) {
ctx.error = { method: 'create', err: redisAttrs.err };
return;
}
if (Object.keys(this.schema[collection].definition).sort().join(':') !==
Object.keys(redisAttrs.val).sort().join(':')) {
ctx.error = { method: 'create', err: 'badParameter' };
return;
}
genCode(ctx, `local id = redis.call('INCR', '${this._keyPrefix}:${collection}:nextid')`);
genCode(ctx, `local key = '${this._keyPrefix}:${collection}:' .. id`);
this._addValuesVar(ctx, redisAttrs.val);
this._addIndices(ctx, collection, 'create');
genCode(ctx, `hmset(key, values)`);
genCode(ctx, `redis.call('ZADD', '${this._keyPrefix}:${collection}:ids', id, id)`);
genCode(ctx, `ret = { 'create', 'noError', id }`);
};
RigidDB.prototype._update = function(ctx, collection, id, attrs) {
let redisAttrs = this._normalizeRedisAttrs(collection, attrs);
if (redisAttrs.err) {
ctx.error = { method: 'update', err: redisAttrs.err };
return;
}
genCode(ctx, `local id = ARGV[${ctx.paramCounter++}]`);
pushParams(ctx, id);
genCode(ctx, `local key = '${this._keyPrefix}:${collection}:' .. id`);
genCode(ctx, `if redis.call("EXISTS", key) == 0 then return { 'update', 'notFound' } end`);
genCode(ctx, `local values = hgetall(key)`);
genCode(ctx, `local chg = 0`);
for (let prop in redisAttrs.val) {
genCode(ctx, `if values['${prop}'] ~= ARGV[${ctx.paramCounter}] then chg = chg + 1 end`);
genCode(ctx, `values['${prop}'] = ARGV[${ctx.paramCounter++}]`);
pushParams(ctx, redisAttrs.val[prop]);
}
let indices = this._genAllIndices(ctx, collection);
this._assertUniqIndicesFree(ctx, collection, indices, 'update');
genCode(ctx, `values = hgetall(key)`);
this._removeIndices(ctx, collection, 'update');
for (let prop in redisAttrs.val) {
genCode(ctx, `values['${prop}'] = ARGV[${ctx.paramCounter++}]`);
pushParams(ctx, redisAttrs.val[prop]);
}
this._addIndices(ctx, collection, 'update');
genCode(ctx, `hmset(key, values)`);
genCode(ctx, `ret = { 'update', 'noError', chg }`);
};
RigidDB.prototype._delete = function(ctx, collection, id) {
genCode(ctx, `local id = ARGV[${ctx.paramCounter++}]`);
genCode(ctx, `local key = '${this._keyPrefix}:${collection}:' .. id`);
genCode(ctx, `if redis.call("EXISTS", key) == 0 then return { 'delete', 'notFound' } end`);
genCode(ctx, `local values = hgetall(key)`);
this._removeIndices(ctx, collection, 'delete');
genCode(ctx, `redis.call('ZREM', '${this._keyPrefix}:${collection}:ids', id)`);
genCode(ctx, `redis.call('DEL', key)`);
genCode(ctx, `ret = { 'delete', 'noError' }`);
pushParams(ctx, id);
};
RigidDB.prototype._get = function(ctx, collection, id) {
genCode(ctx, `local key = '${this._keyPrefix}:${collection}:' .. ARGV[${ctx.paramCounter++}]`);
genCode(ctx, `if redis.call("EXISTS", key) == 0 then return { 'get', 'notFound' } end`);
genCode(ctx, `ret = { 'get', 'noError', redis.call('HGETALL', key), '${collection}' }`);
pushParams(ctx, id);
};
RigidDB.prototype._exists = function(ctx, collection, id) {
genCode(ctx, `local key = '${this._keyPrefix}:${collection}:' .. ARGV[${ctx.paramCounter++}]`);
genCode(ctx, `if redis.call("EXISTS", key) == 0 then return { 'exists', 'noError', 0 } end`);
genCode(ctx, `ret = { 'exists', 'noError', 1 }`);
pushParams(ctx, id);
};
RigidDB.prototype._size = function(ctx, collection) {
genCode(ctx, `local key = '${this._keyPrefix}:${collection}:ids'`);
genCode(ctx, `if redis.call("EXISTS", key) == 0 then return { 'size', 'noError', 0 } end`);
genCode(ctx, `ret = { 'size', 'noError', redis.call('ZCARD', key) }`);
};
RigidDB.prototype._currentId = function(ctx, collection) {
genCode(ctx, `local key = '${this._keyPrefix}:${collection}:nextid'`);
genCode(ctx, `ret = { 'currentId', 'noError', redis.call('GET', key) or 0 }`);
};
RigidDB.prototype._list = function(ctx, collection) {
genCode(ctx, `local key = '${this._keyPrefix}:${collection}:ids'`);
genCode(ctx, `ret = { 'list', 'noError', redis.call("ZRANGE", key, 0, -1) }`);
};
RigidDB.prototype._find = function(ctx, collection, attrs) {
let indices = this.schema[collection].indices;
let searchFields = Object.keys(attrs).sort().join();
let index = false;
for (let indexName in indices) {
let candidateIndex = indices[indexName];
if (candidateIndex.fields.map(field => field.name).sort().join() === searchFields) {
index = candidateIndex;
break;
}
}
if (!index) {
ctx.error = { method: 'find', err: 'unknownIndex' };
return;
}
let redisAttrs = this._normalizeRedisAttrs(collection, attrs);
if (redisAttrs.err) {
ctx.error = { method: 'find', err: redisAttrs.err };
return;
}
this._addValuesVar(ctx, redisAttrs.val);
let name = this._indexName(collection, index);
let prop = this._indexValues(index);
genCode(ctx, `local result = redis.call('HGET', '${name}', ${prop})`);
genCode(ctx, `if result ~= false then`);
genCode(ctx, `result = { result }`);
genCode(ctx, `else`);
genCode(ctx, `result = redis.call('SMEMBERS', '${name}:' .. ${prop})`);
genCode(ctx, `end`);
genCode(ctx, `ret = { 'find', 'noError', result }`);
};
RigidDB.prototype._genAllIndices = function(ctx, collection) {
let indices = this.schema[collection].indices;
let redisIndices = [];
// { name: "color:mileage", value: 'red:423423', uniq: false }
for (let indexName in indices) {
let index = indices[indexName];
redisIndices.push({
name: indexName,
redisKey: this._indexName(collection, index),
redisValue: this._indexValues(index),
fields: index.fields,
uniq: index.uniq
});
}
return redisIndices;
};
RigidDB.prototype._indexName = function(collection, index) {
let fields = index.fields.map(field => field.name).sort().join(':');
return `${this._keyPrefix}:${collection}:i:${fields}`;
};
RigidDB.prototype._indexValues = function(index) {
let compareFunc = (a, b) => (a.name < b.name) ? -1 : ((a.name > b.name) ? 1 : 0);
return index.fields.sort(compareFunc).map(field => {
let valueCode = `values["${field.name}"]`;
if (field.caseInsensitive) {
valueCode = `string.lower(${valueCode})`;
}
// Lua gsub returns two values. Extra parenthesis are used to discard the second value.
return `(string.gsub(${valueCode}, ':', '::'))`;
}).join(`..':'..`);
};
RigidDB.prototype._assertUniqIndicesFree = function(ctx, collection, indices, method) {
genCode(ctx, `local nonUniqIndices, uniqError = {}, false`);
for (let index of indices) {
if (index.uniq) {
let notNullCheck = index.fields.map(field => `values["${field.name}"] ~= '~'`).join(' and ');
genCode(ctx, `local currentIndex = redis.call('HGET', '${index.redisKey}', ${index.redisValue})`);
genCode(ctx, `if currentIndex and currentIndex ~= id and ${notNullCheck} then`);
genCode(ctx, `table.insert(nonUniqIndices, '${index.name}')`);
genCode(ctx, `uniqError = true`);
genCode(ctx, `end`);
}
}
genCode(ctx, `if uniqError then`);
genCode(ctx, `return { '${method}', 'notUnique', nonUniqIndices }`);
genCode(ctx, `end`);
return indices;
};
RigidDB.prototype._addIndices = function(ctx, collection, method) {
let indices = this._genAllIndices(ctx, collection);
this._assertUniqIndicesFree(ctx, collection, indices, method);
for (let index of indices) {
genCode(ctx, `local hashId = redis.call('HGET', '${index.redisKey}', ${index.redisValue})`);
genCode(ctx, `local isSet = redis.call('EXISTS', '${index.redisKey}:' .. ${index.redisValue})`);
genCode(ctx, `if not hashId and isSet == 0 then `);
genCode(ctx, `redis.call('HSET', '${index.redisKey}', ${index.redisValue}, id)`);
genCode(ctx, `elseif isSet == 0 then`);
genCode(ctx, `redis.call('HDEL', '${index.redisKey}', ${index.redisValue})`);
genCode(ctx, `redis.call('SADD', '${index.redisKey}:' .. ${index.redisValue}, id, hashId)`);
genCode(ctx, `else`);
genCode(ctx, `redis.call('SADD', '${index.redisKey}:' .. ${index.redisValue}, id)`);
genCode(ctx, `end`);
}
};
RigidDB.prototype._removeIndices = function(ctx, collection) {
let indices = this._genAllIndices(ctx, collection);
for (let index of indices) {
genCode(ctx, `local removed = redis.call('HDEL', '${index.redisKey}', ${index.redisValue})`);
genCode(ctx, `if removed == 0 then`);
genCode(ctx, `redis.call('SREM', '${index.redisKey}:' .. ${index.redisValue}, id)`);
genCode(ctx, `local remaining = redis.call('SCARD', '${index.redisKey}:' .. ${index.redisValue})`);
genCode(ctx, `if remaining == 1 then`);
genCode(ctx, `local last = redis.call('SMEMBERS', '${index.redisKey}:' .. ${index.redisValue})`);
genCode(ctx, `redis.call('DEL', '${index.redisKey}:' .. ${index.redisValue})`);
genCode(ctx, `redis.call('HSET', '${index.redisKey}', ${index.redisValue}, last[1])`);
genCode(ctx, `end`);
genCode(ctx, `end`);
}
};
RigidDB.prototype._addValuesVar = function(ctx, attrs) {
genCode(ctx, `local values = {`);
for (let prop in attrs) {
genCode(ctx, `['${prop}'] = ARGV[${ctx.paramCounter++}],`);
pushParams(ctx, attrs[prop]);
}
genCode(ctx, `}`);
};
RigidDB.prototype._processRedisGetReturnValue = function(collection, redisRetVal) {
let redisObject = {};
while (redisRetVal.length > 0) {
let prop = redisRetVal.shift();
redisObject[prop] = redisRetVal.shift();
}
return this._deNormalizeRedisAttrs(collection, redisObject);
};
RigidDB.prototype._processRedisAttrsForPrinting = function(collection, redisObject) {
redisObject = this._deNormalizeRedisAttrs(collection, redisObject);
for (let prop in redisObject) {
let redisVal = redisObject[prop];
let propType = this.schema[collection].definition[prop].type;
if (redisVal === null) {
redisObject[prop] = '[NULL]';
} else if (propType === 'string') {
redisObject[prop] = `"${redisVal}"`;
} else {
redisObject[prop] = redisVal.toString();
}
}
return redisObject;
};
RigidDB.prototype._normalizeRedisAttrs = function(collection, attrs) {
let redisAttrs = {};
let schema = this.schema[collection].definition;
for (let prop in attrs) {
let definition = schema[prop];
let propVal = attrs[prop];
let redisVal;
if (!definition) {
continue;
}
if (propVal === null) {
if (!definition.allowNull) {
return { err: `nullNotAllowed` };
}
redisVal = '~';
} else {
if ((definition.type === 'boolean' && typeof(propVal) !== 'boolean') ||
(definition.type === 'int' && !Number.isFinite(propVal)) ||
(definition.type === 'string' && typeof(propVal) !== 'string') ||
(definition.type === 'date' && !(propVal instanceof Date)) ||
(definition.type === 'timestamp' && !(propVal instanceof Date))) {
return { err: 'wrongType' };
}
switch (definition.type) {
case 'boolean':
redisVal = propVal ? 'true' : 'false';
break;
case 'int':
redisVal = propVal.toString();
break;
case 'string':
redisVal = (/^~+$/.test(propVal)) ? `~${propVal}` : propVal;
break;
case 'date':
redisVal = propVal.toString();
break;
case 'timestamp':
redisVal = propVal.getTime().toString();
break;
}
}
redisAttrs[prop] = redisVal;
}
return { val: redisAttrs };
};
RigidDB.prototype._deNormalizeRedisAttrs = function(collection, redisObject) {
for (let prop in redisObject) {
let redisVal = redisObject[prop];
let propType = this.schema[collection].definition[prop].type;
if (redisVal === '~') {
redisObject[prop] = null;
} else {
switch (propType) {
case 'boolean':
redisObject[prop] = redisObject[prop] === 'true';
break;
case 'int':
redisObject[prop] = parseInt(redisVal);
break;
case 'string':
if (/^~+$/.test(redisVal)) {
redisObject[prop] = redisObject[prop].substring(1);
}
break;
case 'date':
redisObject[prop] = new Date(redisObject[prop]);
break;
case 'timestamp':
redisObject[prop] = new Date(parseInt(redisObject[prop]));
break;
}
}
}
return redisObject;
};
Object.defineProperty(RigidDB.prototype, '_keyPrefix', {
get: function() {
return `${this.prefix}-${this.revision}`;
}
});
function newContext() {
return {
paramCounter: 1,
params: [],
script: '',
error: false
};
}
function genCode(ctx, lua) {
ctx.script += `${lua}\n`;
}
function pushParams(ctx, params) {
ctx.params.push(params);
}
function onlyLetters(str) {
return /^[a-zA-Z]+$/.test(str);
}
function onlyLettersNumbersDashes(str) {
return /^[a-zA-Z0-9_\-]+$/.test(str);
}
function utilityFuncs() {
return `
local hgetall = function (key)
local bulk = redis.call('HGETALL', key)
local result = {}
local nextkey
for i, v in ipairs(bulk) do
if i % 2 == 1 then
nextkey = v
else
result[nextkey] = v
end
end
return result
end
local hmget = function (key, ...)
if next(arg) == nil then return {} end
local bulk = redis.call('HMGET', key, unpack(arg))
local result = {}
for i, v in ipairs(bulk) do result[ arg[i] ] = v end
return result
end
local hmset = function (key, dict)
if next(dict) == nil then return nil end
local bulk = {}
for k, v in pairs(dict) do
table.insert(bulk, k)
table.insert(bulk, v)
end
return redis.call('HMSET', key, unpack(bulk))
end
`;
}
module.exports = RigidDB;