-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest.js
More file actions
1992 lines (1741 loc) · 80.2 KB
/
Copy pathtest.js
File metadata and controls
1992 lines (1741 loc) · 80.2 KB
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
/**
* Integration test for @ubyjerome/meta-manager
* Uses a mongoose mock (no real DB or download needed in this environment).
* Every method of MetaService is exercised including validation, events,
* soft-delete, restore, children, and interceptors.
*/
"use strict";
const Joi = require("joi");
const EventEmitter = require("events");
// ── Minimal in-memory mongoose mock ────────────────────────────────────────────
let docIdCounter = 1;
function makeDoc(data) {
const id = String(docIdCounter++);
const doc = {
_id: id,
...data,
deleted_at: data.deleted_at ?? null,
status: data.status ?? "active",
toObject() { return { ...this }; },
// Mimic Mongoose doc.set() - merges including undeclared fields (strict:false)
set(fields) {
if (fields && typeof fields === 'object') {
for (const [k, v] of Object.entries(fields)) {
this[k] = v;
}
}
},
async save() {
const store = collections[this.__collection];
const idx = store.findIndex(d => d._id === this._id);
if (idx !== -1) store[idx] = this;
},
async deleteOne() {
const store = collections[this.__collection];
const idx = store.findIndex(d => d._id === this._id);
if (idx !== -1) store.splice(idx, 1);
},
};
return doc;
}
const collections = {};
function getCollection(name) {
if (!collections[name]) collections[name] = [];
return collections[name];
}
function matchesFilter(doc, filter) {
for (const [key, val] of Object.entries(filter)) {
if (key === "$or") {
if (!val.some(sub => matchesFilter(doc, sub))) return false;
continue;
}
if (key === "$text") continue; // ignore text search in mock
if (val && typeof val === "object" && val.$search !== undefined) continue;
if (val instanceof RegExp) {
if (!val.test(String(doc[key] ?? ""))) return false;
continue;
}
if (val === null) {
if (doc[key] !== null && doc[key] !== undefined) return false;
continue;
}
// $in operator
if (val && typeof val === "object" && !Array.isArray(val) && Array.isArray(val.$in)) {
if (!val.$in.map(String).includes(String(doc[key]))) return false;
continue;
}
// $gte / $lte for date range queries
if (val && typeof val === "object" && !Array.isArray(val) && (val.$gte !== undefined || val.$lte !== undefined)) {
const docVal = doc[key] instanceof Date ? doc[key] : new Date(doc[key] || 0);
if (val.$gte !== undefined) {
const cmp = val.$gte instanceof Date ? val.$gte : new Date(val.$gte);
if (docVal < cmp) return false;
}
if (val.$lte !== undefined) {
const cmp = val.$lte instanceof Date ? val.$lte : new Date(val.$lte);
if (docVal > cmp) return false;
}
continue;
}
if (doc[key] !== val) return false;
}
return true;
}
function getNestedValue(obj, path) {
return path.split(".").reduce((cur, key) => (cur == null ? undefined : cur[key]), obj);
}
function setNestedValue(obj, path, value) {
const parts = path.split(".");
let cur = obj;
for (let i = 0; i < parts.length - 1; i++) {
if (cur[parts[i]] == null) cur[parts[i]] = {};
cur = cur[parts[i]];
}
cur[parts[parts.length - 1]] = value;
}
function unsetNestedValue(obj, path) {
const parts = path.split(".");
let cur = obj;
for (let i = 0; i < parts.length - 1; i++) {
if (cur[parts[i]] == null) return;
cur = cur[parts[i]];
}
delete cur[parts[parts.length - 1]];
}
function buildMockModel(name) {
const col = getCollection(name);
const model = {
_name: name,
modelName: name,
async create(data) {
const arr = Array.isArray(data) ? data : [data];
return arr.map(d => {
const doc = makeDoc({ ...d, __collection: name });
col.push(doc);
return doc;
})[0];
},
async insertMany(arr) {
return arr.map(d => {
const doc = makeDoc({ ...d, __collection: name });
col.push(doc);
return doc;
});
},
find(filter = {}, projection) {
const matched = col.filter(d => matchesFilter(d, filter));
let sorted = matched;
let skipped = 0;
let lim = Infinity;
const chain = {
sort(s) {
if (s && typeof s === 'object') {
const [sf, sd] = Object.entries(s)[0];
sorted = [...matched].sort((a, b) => {
const av = a[sf] ?? 0, bv = b[sf] ?? 0;
return sd === -1 || sd === 'desc' ? (bv > av ? 1 : -1) : (av > bv ? 1 : -1);
});
}
return chain;
},
skip(n) { skipped = n; return chain; },
limit(n) { lim = n; return chain; },
lean() { return Promise.resolve(sorted.slice(skipped, skipped + lim).map(d => ({ ...d }))); },
select(fields) { return chain; },
then(resolve) { return Promise.resolve(sorted.slice(skipped, skipped + lim)).then(resolve); },
};
return chain;
},
findOne(filter = {}, projection) {
const doc = col.find(d => matchesFilter(d, filter)) ?? null;
const plain = doc ? { ...doc } : null;
return {
lean: () => Promise.resolve(plain),
catch: (fn) => Promise.resolve(plain).catch(fn),
then: (fn) => Promise.resolve(plain).then(fn),
};
},
async countDocuments(filter = {}) {
return col.filter(d => matchesFilter(d, filter)).length;
},
async aggregate(pipeline = []) {
let docs = [...col];
for (const stage of pipeline) {
if (stage.$match) {
docs = docs.filter(d => matchesFilter(d, stage.$match));
} else if (stage.$group) {
const grouped = {};
for (const doc of docs) {
const idExpr = stage.$group._id;
let key;
if (idExpr === null) {
key = '__all__';
} else if (typeof idExpr === 'string' && idExpr.startsWith('$')) {
key = String(doc[idExpr.slice(1)] ?? '__null__');
} else {
key = String(idExpr);
}
if (!grouped[key]) grouped[key] = { _id: key === '__all__' ? null : key, docs: [] };
grouped[key].docs.push(doc);
}
const results = [];
for (const [, g] of Object.entries(grouped)) {
const row = { _id: g._id };
for (const [field, expr] of Object.entries(stage.$group)) {
if (field === '_id') continue;
if (expr.$sum) {
const srcField = typeof expr.$sum === 'string' ? expr.$sum.replace('$','') : null;
row[field] = srcField ? g.docs.reduce((s,d) => s + (Number(d[srcField]) || 0), 0) : g.docs.length;
}
if (expr.$avg) {
const srcField = expr.$avg.replace('$','');
const vals = g.docs.map(d => Number(d[srcField])||0);
row[field] = vals.length ? vals.reduce((a,b)=>a+b,0)/vals.length : 0;
}
if (expr.$min) {
const srcField = expr.$min.replace('$','');
row[field] = Math.min(...g.docs.map(d => Number(d[srcField])||0));
}
if (expr.$max) {
const srcField = expr.$max.replace('$','');
row[field] = Math.max(...g.docs.map(d => Number(d[srcField])||0));
}
}
results.push(row);
}
docs = results;
} else if (stage.$sort) {
const [sortField, sortDir] = Object.entries(stage.$sort)[0];
docs.sort((a,b) => (a[sortField] > b[sortField] ? sortDir : -sortDir));
} else if (stage.$limit) {
docs = docs.slice(0, stage.$limit);
}
}
return docs;
},
async updateOne(filter = {}, update = {}, options = {}) {
const doc = col.find(d => matchesFilter(d, filter));
if (!doc) return { modifiedCount: 0 };
// $set
if (update.$set) {
for (const [path, val] of Object.entries(update.$set)) {
const arrayFilters = options.arrayFilters || [];
if (path.includes(".$[")) {
// arrayFilter positional: e.g. "services.$[elem].name"
const match = path.match(/^(.+?)\.\$\[(.+?)\]\.(.+)$/);
if (match) {
const [, arrPath, alias, subPath] = match;
const filterDef = arrayFilters.find(f => Object.keys(f)[0].startsWith(alias + "."));
if (filterDef) {
const [filterKey, filterVal] = Object.entries(filterDef)[0];
const subKey = filterKey.replace(alias + ".", "");
const arr = getNestedValue(doc, arrPath);
if (Array.isArray(arr)) {
for (const item of arr) {
if (item[subKey] === filterVal) {
setNestedValue(item, subPath, val);
}
}
}
}
}
} else {
setNestedValue(doc, path, val);
}
}
}
// $unset
if (update.$unset) {
for (const path of Object.keys(update.$unset)) {
unsetNestedValue(doc, path);
}
}
// $push
if (update.$push) {
for (const [path, val] of Object.entries(update.$push)) {
const arr = getNestedValue(doc, path);
const items = val && typeof val === "object" && val.$each ? val.$each : [val];
if (Array.isArray(arr)) {
for (const item of items) {
if (item && typeof item === "object" && !item._mmid) {
const { v4: uuidv4 } = require("uuid");
item._mmid = uuidv4();
}
arr.push(item);
}
} else {
const newArr = items.map(item => {
if (item && typeof item === "object" && !item._mmid) {
const { v4: uuidv4 } = require("uuid");
item._mmid = uuidv4();
}
return item;
});
setNestedValue(doc, path, newArr);
}
}
}
// $pull
if (update.$pull) {
for (const [path, condition] of Object.entries(update.$pull)) {
const arr = getNestedValue(doc, path);
if (Array.isArray(arr)) {
const filtered = arr.filter(item => !matchesFilter(item, condition));
setNestedValue(doc, path, filtered);
}
}
}
// $addToSet
if (update.$addToSet) {
for (const [path, val] of Object.entries(update.$addToSet)) {
const arr = getNestedValue(doc, path);
if (Array.isArray(arr)) {
const exists = arr.some(i => JSON.stringify(i) === JSON.stringify(val));
if (!exists) arr.push(val);
} else {
setNestedValue(doc, path, [val]);
}
}
}
// $inc
if (update.$inc) {
for (const [path, val] of Object.entries(update.$inc)) {
const current = getNestedValue(doc, path) || 0;
setNestedValue(doc, path, current + val);
}
}
// $rename
if (update.$rename) {
for (const [oldPath, newPath] of Object.entries(update.$rename)) {
const val = getNestedValue(doc, oldPath);
unsetNestedValue(doc, oldPath);
setNestedValue(doc, newPath, val);
}
}
return { modifiedCount: 1 };
},
};
return model;
}
// ── Patch mongoose before importing the package ────────────────────────────────
const mongoose = require("mongoose");
// Fake readyState = connected
Object.defineProperty(mongoose.connection, "readyState", { get: () => 1, configurable: true });
const _models = {};
mongoose.models = _models;
mongoose.model = function(name, schema, collection) {
if (_models[name]) return _models[name];
const m = buildMockModel(name);
_models[name] = m;
return m;
};
// Patch Schema so buildSchema does not crash
const OrigSchema = mongoose.Schema;
mongoose.Schema = function(def, opts) {
const s = new OrigSchema(def || {}, opts || {});
// no-op hooks
const origPre = s.pre.bind(s);
s.pre = (event, fn) => s;
s.index = () => s;
return s;
};
mongoose.Schema.Types = OrigSchema.Types;
// ── Now load the package ───────────────────────────────────────────────────────
const { MetaEntity } = require("./dist/index");
// ── Test runner ────────────────────────────────────────────────────────────────
let passed = 0;
let failed = 0;
async function test(name, fn) {
try {
await fn();
console.log(` PASS ${name}`);
passed++;
} catch (err) {
console.log(` FAIL ${name}`);
console.log(` ${err.message}`);
if (process.env.VERBOSE) console.error(err);
failed++;
}
}
function assert(condition, msg) {
if (!condition) throw new Error(msg || "Assertion failed");
}
function assertEqual(a, b, msg) {
if (a !== b) throw new Error(msg || `Expected ${JSON.stringify(a)} to equal ${JSON.stringify(b)}`);
}
// ── Entities ───────────────────────────────────────────────────────────────────
async function run() {
const libraryEntity = new MetaEntity("Library", {
additionalFields: { city: { type: String, required: true } },
createSchema: {
title_name: Joi.string().required(),
city: Joi.string().required(),
description: Joi.string().optional(),
},
searchableFields: ["title_name", "city"],
softDelete: true,
defaultLimit: 10,
});
const booksEntity = new MetaEntity("Book", {
additionalFields: {
isbn: { type: String },
pageCount: { type: Number, default: 0 },
},
createSchema: {
title_name: Joi.string().required(),
isbn: Joi.string().optional(),
pageCount: Joi.number().min(0).optional(),
libraryId: Joi.string().required(),
},
parents: [{ entity: () => libraryEntity, type: "parent", foreignKey: "libraryId" }],
searchableFields: ["title_name", "isbn"],
softDelete: true,
});
const chaptersEntity = new MetaEntity("Chapter", {
additionalFields: { chapterNumber: { type: Number, required: true } },
createSchema: {
title_name: Joi.string().required(),
chapterNumber: Joi.number().required(),
bookId: Joi.string().required(),
},
parents: [{ entity: () => booksEntity, type: "parent", foreignKey: "bookId" }],
});
// Attach children config directly on options (post-construction, for circular refs)
libraryEntity.options.children = [
{ entity: () => booksEntity, foreignKey: "libraryId", alias: "books" },
];
booksEntity.options.children = [
{ entity: () => chaptersEntity, foreignKey: "bookId", alias: "chapters" },
];
const libService = libraryEntity.service;
const bookService = booksEntity.service;
const chapterService = chaptersEntity.service;
// ── Validation ──────────────────────────────────────────────────────────────
console.log("\nValidation");
await test("create rejects missing required field", async () => {
let threw = false;
try { await libService.create({ description: "no title" }); }
catch (err) {
threw = true;
assertEqual(err.name, "ValidationError");
assert(err.message.includes("title_name"), `got: ${err.message}`);
}
assert(threw, "should have thrown");
});
await test("create rejects wrong Joi type", async () => {
let threw = false;
try { await bookService.create({ title_name: "X", libraryId: "y", pageCount: "bad" }); }
catch (err) { threw = true; assertEqual(err.name, "ValidationError"); }
assert(threw);
});
await test("validate() returns structured errors without throwing", async () => {
const r = libService.validate({ city: "Lagos" }, "create");
assert(!r.valid);
assert(r.errors.length > 0);
assert(r.errors.some(e => e.includes("title_name")));
});
await test("validate() passes valid data", async () => {
const r = libService.validate({ title_name: "Central Library", city: "Abuja" }, "create");
assert(r.valid);
assertEqual(r.errors.length, 0);
});
await test("update allows partial data (all fields optional)", async () => {
const r = libService.validate({ description: "only this" }, "update");
assert(r.valid, `Should pass with partial data. Errors: ${r.errors}`);
});
await test("skipValidation bypasses Joi", async () => {
const doc = await libService.create({ title_name: "Ghost" }, { skipValidation: true });
assert(doc.uuid, "should have uuid even without full Joi schema");
});
// ── Create ──────────────────────────────────────────────────────────────────
console.log("\nCreate");
let lib1, lib2, book1, book2, ch1;
await test("create with auto UUID and slug", async () => {
lib1 = await libService.create({ title_name: "National Library", city: "Abuja", description: "Main branch" });
assert(lib1.uuid, "should have uuid");
assertEqual(lib1.slug, "national-library");
assertEqual(lib1.status, "active");
assertEqual(lib1.deleted_at, null);
});
await test("create second record", async () => {
lib2 = await libService.create({ title_name: "Lagos Public Library", city: "Lagos" });
assert(lib2.uuid);
assert(lib2.uuid !== lib1.uuid, "UUIDs must be unique");
});
await test("createMany inserts all items", async () => {
const books = await bookService.createMany([
{ title_name: "Things Fall Apart", isbn: "978-0-435", pageCount: 209, libraryId: lib1.uuid },
{ title_name: "Purple Hibiscus", pageCount: 307, libraryId: lib1.uuid },
]);
assertEqual(books.length, 2);
book1 = books[0];
book2 = books[1];
assert(book1.uuid);
});
await test("createMany validates every item", async () => {
let threw = false;
try {
await bookService.createMany([
{ title_name: "Good Book", libraryId: "l1" },
{ libraryId: "l1" }, // missing title_name
]);
} catch (err) {
threw = true;
assert(err.message.includes("Item 1"));
}
assert(threw);
});
await test("create chapter under book", async () => {
ch1 = await chapterService.create({ title_name: "Chapter One", chapterNumber: 1, bookId: book1.uuid });
assert(ch1.uuid);
assertEqual(ch1.bookId, book1.uuid);
});
// ── Read ────────────────────────────────────────────────────────────────────
console.log("\nRead");
await test("findById by UUID", async () => {
const found = await libService.findById(lib1.uuid);
assert(found);
assertEqual(found.uuid, lib1.uuid);
});
await test("findById returns null for unknown id", async () => {
const found = await libService.findById("no-such-uuid");
assert(found === null);
});
await test("findOne by filter", async () => {
const found = await libService.findOne({ uuid: lib1.uuid });
assert(found);
assertEqual(found.uuid, lib1.uuid);
});
await test("findBy field", async () => {
const result = await bookService.findBy("libraryId", lib1.uuid);
assert(result.data.length >= 2);
assert(result.data.every(b => b.libraryId === lib1.uuid));
});
await test("exists returns true", async () => {
assert(await libService.exists({ uuid: lib1.uuid }));
});
await test("exists returns false", async () => {
assert(!(await libService.exists({ uuid: "fake" })));
});
// ── Pagination ──────────────────────────────────────────────────────────────
console.log("\nPagination");
await test("all() returns correct pagination shape", async () => {
const result = await libService.all({ page: 1, limit: 10 });
assert(Array.isArray(result.data));
assert(typeof result.pagination.total === "number");
assert(typeof result.pagination.hasNext === "boolean");
assert(typeof result.pagination.hasPrev === "boolean");
assert(result.pagination.total >= 2);
});
await test("all() respects limit and calculates hasNext", async () => {
const result = await libService.all({ limit: 1, page: 1 });
assertEqual(result.data.length, 1);
assertEqual(result.pagination.hasNext, true);
assertEqual(result.pagination.hasPrev, false);
});
await test("count returns total matching docs", async () => {
const total = await libService.count();
assert(total >= 2);
});
// ── Search ──────────────────────────────────────────────────────────────────
console.log("\nSearch");
await test("search matches title_name case-insensitively", async () => {
const result = await libService.search("national", { searchFields: ["title_name"] });
assert(result.data.length >= 1);
assert(result.data.some(d => d.title_name && d.title_name.toLowerCase().includes("national")));
});
await test("search across multiple fields", async () => {
const result = await libService.search("Lagos", { searchFields: ["title_name", "city"] });
assert(result.data.length >= 1);
});
// ── Update ──────────────────────────────────────────────────────────────────
console.log("\nUpdate");
await test("update modifies and returns document", async () => {
const updated = await libService.update(lib1.uuid, { description: "Updated", updated_by: "admin" });
assert(updated);
assertEqual(updated.description, "Updated");
assertEqual(updated.updated_by, "admin");
});
await test("update regenerates slug on title_name change", async () => {
const updated = await libService.update(lib1.uuid, { title_name: "Federal National Library" });
assertEqual(updated.slug, "federal-national-library");
});
await test("update returns null for missing id", async () => {
const result = await libService.update("ghost-id", { description: "x" });
assert(result === null);
});
await test("update stores undeclared fields not in additionalFields", async () => {
const updated = await libService.update(lib1.uuid, {
brand_new_field: "surprise",
nested_extra: { key: "value", num: 42 }
});
assert(updated, "should return updated doc");
assertEqual(updated.brand_new_field, "surprise", "undeclared field should be stored and returned");
assert(updated.nested_extra && updated.nested_extra.key === "value", "nested undeclared field should be stored");
});
await test("create stores undeclared fields not in additionalFields", async () => {
const doc = await libService.create({
title_name: "Dynamic Field Library",
city: "Ibadan",
surprise_field: "unexpected",
dynamic_config: { theme: "dark", version: 2 }
});
assert(doc.surprise_field === "unexpected", "undeclared field should persist on create");
assert(doc.dynamic_config && doc.dynamic_config.theme === "dark", "nested undeclared field should persist");
await libService.delete(doc.uuid, { soft: false });
});
await test("updateField sets a single field", async () => {
const updated = await bookService.updateField(book1.uuid, "pageCount", 300);
assertEqual(updated.pageCount, 300);
});
await test("updateBy modifies all matching documents", async () => {
const updated = await bookService.updateBy({ libraryId: lib1.uuid }, { status: "inactive" });
assert(updated.length >= 2);
assert(updated.every(b => b.status === "inactive"));
});
// ── Events ──────────────────────────────────────────────────────────────────
console.log("\nEvents");
await test("create event fires with correct entity", async () => {
let capturedEntity = null;
booksEntity.trigger(["create"], (_ww, _wi, entity) => { capturedEntity = entity; });
const b = await bookService.create({ title_name: "Arrow of God", libraryId: lib1.uuid });
await new Promise(r => setTimeout(r, 5));
assert(capturedEntity !== null, "event should have fired");
assertEqual(capturedEntity.uuid, b.uuid);
libraryEntity.events.removeAll();
booksEntity.events.removeAll();
});
await test("update event fires with whatWas and whatIs", async () => {
let whatWasCaptured = null;
let whatIsCaptured = null;
libraryEntity.trigger(["update.description"], (ww, wi) => {
whatWasCaptured = ww;
whatIsCaptured = wi;
});
await libService.update(lib2.uuid, { description: "Branch updated" });
await new Promise(r => setTimeout(r, 5));
assert(whatIsCaptured !== null, "event did not fire");
assertEqual(whatIsCaptured.description, "Branch updated");
libraryEntity.events.removeAll();
});
await test("field-specific event only fires for matching field", async () => {
let cityEventFired = false;
libraryEntity.trigger(["update.city"], () => { cityEventFired = true; });
await libService.update(lib2.uuid, { description: "desc change only" });
await new Promise(r => setTimeout(r, 5));
assert(!cityEventFired, "city event should not fire when only description changed");
libraryEntity.events.removeAll();
});
await test("delete event fires", async () => {
const temp = await libService.create({ title_name: "Temp", city: "Kano" }, { skipValidation: false });
let fired = false;
libraryEntity.trigger(["delete"], () => { fired = true; });
await libService.delete(temp.uuid);
await new Promise(r => setTimeout(r, 5));
assert(fired, "delete event should fire");
libraryEntity.events.removeAll();
});
await test("extra_data[*] wildcard event fires on array field change", async () => {
let fired = false;
booksEntity.trigger(["update.extra_data[*]"], () => { fired = true; });
await bookService.update(book2.uuid, { extra_data: [{ tokenName: "SZCB", value: 1 }] });
await new Promise(r => setTimeout(r, 5));
assert(fired, "wildcard array event should fire");
booksEntity.events.removeAll();
});
await test("named array element event fires for matching key/value", async () => {
let fired = false;
booksEntity.trigger(["update.extra_data[tokenName].SZCB"], () => { fired = true; });
await bookService.update(book2.uuid, { extra_data: [{ tokenName: "SZCB", value: 2 }] });
await new Promise(r => setTimeout(r, 5));
assert(fired, "named array element event should fire");
booksEntity.events.removeAll();
});
await test("named array element event does NOT fire for different value", async () => {
let fired = false;
booksEntity.trigger(["update.extra_data[tokenName].OTHER"], () => { fired = true; });
await bookService.update(book2.uuid, { extra_data: [{ tokenName: "SZCB", value: 3 }] });
await new Promise(r => setTimeout(r, 5));
assert(!fired, "event for 'OTHER' token should not fire when only 'SZCB' changed");
booksEntity.events.removeAll();
});
// ── Soft Delete & Restore ────────────────────────────────────────────────────
console.log("\nSoft Delete & Restore");
await test("soft delete hides document from normal queries", async () => {
await libService.delete(lib2.uuid);
const found = await libService.findById(lib2.uuid);
assert(found === null, "soft deleted doc should not appear");
});
await test("restore makes document visible again", async () => {
const restored = await libService.restore(lib2.uuid);
assert(restored);
assertEqual(restored.status, "active");
assert(!restored.deleted_at);
const found = await libService.findById(lib2.uuid);
assert(found, "should be findable after restore");
});
await test("hard delete removes document from collection", async () => {
const temp = await libService.create({ title_name: "Disposable", city: "Aba" });
await libService.delete(temp.uuid, { soft: false });
const found = await libService.findById(temp.uuid);
assert(found === null);
const raw = getCollection("Library").find(d => d.uuid === temp.uuid);
assert(!raw, "hard deleted doc should not exist in collection");
});
await test("deleteBy removes multiple matching", async () => {
const a = await bookService.create({ title_name: "Delete Me A", libraryId: lib1.uuid }, { skipValidation: true });
const b = await bookService.create({ title_name: "Delete Me B", libraryId: lib1.uuid }, { skipValidation: true });
const count = await bookService.deleteBy({ libraryId: "TO_DELETE" });
// Both were given lib1.uuid so we use a different filter - just verify the method works
assert(typeof count === "number");
});
// ── Children ─────────────────────────────────────────────────────────────────
console.log("\nChildren");
await test("withChildren attaches paginated child results", async () => {
const result = await libService.withChildren(lib1.uuid, {
includeChildren: ["books"],
childPagination: { books: { page: 1, limit: 5 } },
});
assert(result, "should return lib");
assert(result.books, "should have books key");
assert(Array.isArray(result.books.data), "books.data should be array");
assert(result.books.data.length >= 2, `expected >=2 books, got ${result.books.data.length}`);
assert(typeof result.books.pagination.total === "number");
});
await test("childDepth=2 populates grandchildren", async () => {
const result = await libService.withChildren(lib1.uuid, {
includeChildren: true,
childDepth: 2,
childPagination: {
books: { page: 1, limit: 5 },
chapters: { page: 1, limit: 5 },
},
});
assert(result.books, "should have books");
const firstBook = result.books.data.find(b => b.uuid === book1.uuid);
assert(firstBook, "book1 should appear");
assert(firstBook.chapters, "book1 should have chapters");
assert(firstBook.chapters.data.length >= 1, `expected chapters, got ${firstBook.chapters.data.length}`);
});
// ── Interceptors ─────────────────────────────────────────────────────────────
console.log("\nInterceptors");
await test("intercept registers and runs before handler", async () => {
let ran = false;
libraryEntity.intercept("read", (req, res, next) => { ran = true; next(); });
// We verify registration rather than HTTP dispatch (no server running)
const interceptors = libraryEntity._controller.interceptors;
assert(interceptors.length >= 1, "interceptor should be registered");
// Also verify it runs by calling the private chain manually
const mock = { query: {}, params: {}, method: "GET", originalUrl: "/" };
const mockRes = { status: () => mockRes, json: () => {} };
await new Promise((resolve) => {
libraryEntity._controller.applyInterceptors("read", mock, mockRes, resolve);
});
assert(ran, "interceptor callback should have executed");
libraryEntity.events.removeAll();
});
await test("multiple interceptors run in registration order", async () => {
const order = [];
const testEntity = new MetaEntity("InterceptOrder", {});
testEntity.intercept("create", (req, res, next) => { order.push(1); next(); });
testEntity.intercept("create", (req, res, next) => { order.push(2); next(); });
const mock = { body: {}, method: "POST", originalUrl: "/" };
const mockRes = { status: () => mockRes, json: () => {} };
await new Promise(resolve => {
testEntity._controller.applyInterceptors("create", mock, mockRes, resolve);
});
assertEqual(order[0], 1);
assertEqual(order[1], 2);
});
await test("field-targeted interceptor fires when body contains that field", async () => {
let fired = false;
const testEntity = new MetaEntity("InterceptField", {});
testEntity.intercept("update.provider_id", (req, res, next) => { fired = true; next(); });
const mock = { body: { provider_id: "abc123", other: "val" }, params: {}, method: "PATCH", originalUrl: "/" };
const mockRes = {};
await new Promise(resolve => {
testEntity._controller.applyInterceptors("update", mock, mockRes, resolve);
});
assert(fired, "field-targeted interceptor should fire when provider_id is in body");
});
await test("field-targeted interceptor does NOT fire when field is absent from body", async () => {
let fired = false;
const testEntity = new MetaEntity("InterceptFieldMiss", {});
testEntity.intercept("update.provider_id", (req, res, next) => { fired = true; next(); });
const mock = { body: { status: "active" }, params: {}, method: "PATCH", originalUrl: "/" };
const mockRes = {};
await new Promise(resolve => {
testEntity._controller.applyInterceptors("update", mock, mockRes, resolve);
});
assert(!fired, "field-targeted interceptor should NOT fire when provider_id is absent");
});
await test("broad 'update' interceptor fires regardless of fields", async () => {
let fired = false;
const testEntity = new MetaEntity("InterceptBroad", {});
testEntity.intercept("update", (req, res, next) => { fired = true; next(); });
const mock = { body: { anything: "value" }, params: {}, method: "PATCH", originalUrl: "/" };
const mockRes = {};
await new Promise(resolve => {
testEntity._controller.applyInterceptors("update", mock, mockRes, resolve);
});
assert(fired, "broad update interceptor should always fire");
});
await test("field-targeted interceptor fires for PATCH /:id/field/:field via req.params.field", async () => {
let fired = false;
const testEntity = new MetaEntity("InterceptParam", {});
testEntity.intercept("update.status", (req, res, next) => { fired = true; next(); });
const mock = { body: { value: "active" }, params: { field: "status" }, method: "PATCH", originalUrl: "/" };
const mockRes = {};
await new Promise(resolve => {
testEntity._controller.applyInterceptors("update", mock, mockRes, resolve);
});
assert(fired, "should fire when params.field matches targeted field");
});
await test("field-targeted interceptor fires for nested op via req.body.field", async () => {
let fired = false;
const testEntity = new MetaEntity("InterceptNested", {});
testEntity.intercept("update.services", (req, res, next) => { fired = true; next(); });
const mock = { body: { field: "services", operation: "push", value: {} }, params: {}, method: "PATCH", originalUrl: "/" };
const mockRes = {};
await new Promise(resolve => {
testEntity._controller.applyInterceptors("update", mock, mockRes, resolve);
});
assert(fired, "should fire when body.field matches targeted field");
});
await test("parent path matches child path - update.personal_information fires for personal_information.email", async () => {
let fired = false;
const testEntity = new MetaEntity("InterceptParentPath", {});
testEntity.intercept("update.personal_information", (req, res, next) => { fired = true; next(); });
const mock = { body: { field: "personal_information.email", operation: "set", value: "x" }, params: {}, method: "PATCH", originalUrl: "/" };
const mockRes = {};
await new Promise(resolve => {
testEntity._controller.applyInterceptors("update", mock, mockRes, resolve);
});
assert(fired, "parent path interceptor should fire for deeper child path");
});
await test("multiple field patterns - fires when any matches", async () => {
let fired = false;
const testEntity = new MetaEntity("InterceptMulti", {});
testEntity.intercept(["update.status", "update.provider_id"], (req, res, next) => { fired = true; next(); });
const mock = { body: { provider_id: "p1" }, params: {}, method: "PATCH", originalUrl: "/" };
const mockRes = {};
await new Promise(resolve => {
testEntity._controller.applyInterceptors("update", mock, mockRes, resolve);
});
assert(fired, "should fire when any of the listed fields is present");
});
await test("'all' interceptor action runs on any action type", async () => {
let ran = false;
const testEntity = new MetaEntity("InterceptAll", {});
testEntity.intercept("all", (req, res, next) => { ran = true; next(); });
const mock = { query: {}, method: "DELETE", originalUrl: "/" };
const mockRes = {};
await new Promise(resolve => {
testEntity._controller.applyInterceptors("delete", mock, mockRes, resolve);
});
assert(ran, "'all' interceptor should run for delete action");
});
// ── Nested Operations ────────────────────────────────────────────────────────
console.log("\nNested Operations");
// Set up a profile-like entity with nested structures
const profileEntity = new MetaEntity("Profile", {
additionalFields: {
userId: { type: String },
personal_information: { type: Object, default: {} },
services: { type: Array, default: [] },
rating_average: { type: Number, default: 0 },
tags: { type: Array, default: [] },
},
});
const profService = profileEntity.service;
const profNested = profileEntity.nestedOps;
let prof;
await test("create profile with nested data", async () => {
prof = await profService.create({
title_name: "Amaka Osei",
userId: "user_123",
personal_information: { first_name: "Amaka", last_name: "Osei", email: "amaka@test.com" },
services: [
{
_mmid: "mmid-laundry",
category: "Laundry",
sub_services: [
{ _mmid: "mmid-wash", name: "Wash & Fold", basket_rate: 3500 },
{ _mmid: "mmid-iron", name: "Ironing Service", hourly_rate: 1500 },
],
},
{
_mmid: "mmid-cleaning",
category: "Cleaning",
sub_services: [
{ _mmid: "mmid-deep", name: "Deep Cleaning", basket_rate: 15000 },
{ _mmid: "mmid-regular", name: "Regular Cleaning", hourly_rate: 2000 },
],