@classytic/mongokit 2.1.0 → 3.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +35 -4
- package/dist/actions/index.d.ts +2 -2
- package/dist/actions/index.js +0 -2
- package/dist/{index-CgOJ2pqz.d.ts → index-CKy3H2SY.d.ts} +1 -1
- package/dist/index.d.ts +10 -6
- package/dist/index.js +183 -6
- package/dist/{memory-cache-DG2oSSbx.d.ts → memory-cache-tn3v1xgG.d.ts} +1 -1
- package/dist/pagination/PaginationEngine.d.ts +1 -1
- package/dist/pagination/PaginationEngine.js +0 -2
- package/dist/plugins/index.d.ts +37 -2
- package/dist/plugins/index.js +173 -3
- package/dist/{types-Nxhmi1aI.d.cts → types-vDtcOhyx.d.ts} +19 -1
- package/dist/utils/index.d.ts +2 -2
- package/dist/utils/index.js +0 -2
- package/package.json +6 -12
- package/dist/actions/index.cjs +0 -479
- package/dist/actions/index.cjs.map +0 -1
- package/dist/actions/index.d.cts +0 -3
- package/dist/actions/index.js.map +0 -1
- package/dist/index-BfVJZF-3.d.cts +0 -337
- package/dist/index.cjs +0 -2142
- package/dist/index.cjs.map +0 -1
- package/dist/index.d.cts +0 -239
- package/dist/index.js.map +0 -1
- package/dist/memory-cache-DqfFfKes.d.cts +0 -142
- package/dist/pagination/PaginationEngine.cjs +0 -375
- package/dist/pagination/PaginationEngine.cjs.map +0 -1
- package/dist/pagination/PaginationEngine.d.cts +0 -117
- package/dist/pagination/PaginationEngine.js.map +0 -1
- package/dist/plugins/index.cjs +0 -874
- package/dist/plugins/index.cjs.map +0 -1
- package/dist/plugins/index.d.cts +0 -275
- package/dist/plugins/index.js.map +0 -1
- package/dist/types-Nxhmi1aI.d.ts +0 -510
- package/dist/utils/index.cjs +0 -667
- package/dist/utils/index.cjs.map +0 -1
- package/dist/utils/index.d.cts +0 -189
- package/dist/utils/index.js.map +0 -1
package/dist/index.cjs
DELETED
|
@@ -1,2142 +0,0 @@
|
|
|
1
|
-
'use strict';
|
|
2
|
-
|
|
3
|
-
Object.defineProperty(exports, '__esModule', { value: true });
|
|
4
|
-
|
|
5
|
-
var mongoose = require('mongoose');
|
|
6
|
-
|
|
7
|
-
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
8
|
-
|
|
9
|
-
var mongoose__default = /*#__PURE__*/_interopDefault(mongoose);
|
|
10
|
-
|
|
11
|
-
var __defProp = Object.defineProperty;
|
|
12
|
-
var __export = (target, all) => {
|
|
13
|
-
for (var name in all)
|
|
14
|
-
__defProp(target, name, { get: all[name], enumerable: true });
|
|
15
|
-
};
|
|
16
|
-
|
|
17
|
-
// src/utils/error.ts
|
|
18
|
-
function createError(status, message) {
|
|
19
|
-
const error = new Error(message);
|
|
20
|
-
error.status = status;
|
|
21
|
-
return error;
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
// src/actions/create.ts
|
|
25
|
-
var create_exports = {};
|
|
26
|
-
__export(create_exports, {
|
|
27
|
-
create: () => create,
|
|
28
|
-
createDefault: () => createDefault,
|
|
29
|
-
createMany: () => createMany,
|
|
30
|
-
upsert: () => upsert
|
|
31
|
-
});
|
|
32
|
-
async function create(Model, data, options = {}) {
|
|
33
|
-
const document = new Model(data);
|
|
34
|
-
await document.save({ session: options.session });
|
|
35
|
-
return document;
|
|
36
|
-
}
|
|
37
|
-
async function createMany(Model, dataArray, options = {}) {
|
|
38
|
-
return Model.insertMany(dataArray, {
|
|
39
|
-
session: options.session,
|
|
40
|
-
ordered: options.ordered !== false
|
|
41
|
-
});
|
|
42
|
-
}
|
|
43
|
-
async function createDefault(Model, overrides = {}, options = {}) {
|
|
44
|
-
const defaults = {};
|
|
45
|
-
Model.schema.eachPath((path, schemaType) => {
|
|
46
|
-
const schemaOptions = schemaType.options;
|
|
47
|
-
if (schemaOptions.default !== void 0 && path !== "_id") {
|
|
48
|
-
defaults[path] = typeof schemaOptions.default === "function" ? schemaOptions.default() : schemaOptions.default;
|
|
49
|
-
}
|
|
50
|
-
});
|
|
51
|
-
return create(Model, { ...defaults, ...overrides }, options);
|
|
52
|
-
}
|
|
53
|
-
async function upsert(Model, query, data, options = {}) {
|
|
54
|
-
return Model.findOneAndUpdate(
|
|
55
|
-
query,
|
|
56
|
-
{ $setOnInsert: data },
|
|
57
|
-
{
|
|
58
|
-
upsert: true,
|
|
59
|
-
new: true,
|
|
60
|
-
runValidators: true,
|
|
61
|
-
session: options.session,
|
|
62
|
-
...options.updatePipeline !== void 0 ? { updatePipeline: options.updatePipeline } : {}
|
|
63
|
-
}
|
|
64
|
-
);
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
// src/actions/read.ts
|
|
68
|
-
var read_exports = {};
|
|
69
|
-
__export(read_exports, {
|
|
70
|
-
count: () => count,
|
|
71
|
-
exists: () => exists,
|
|
72
|
-
getAll: () => getAll,
|
|
73
|
-
getById: () => getById,
|
|
74
|
-
getByQuery: () => getByQuery,
|
|
75
|
-
getOrCreate: () => getOrCreate,
|
|
76
|
-
tryGetByQuery: () => tryGetByQuery
|
|
77
|
-
});
|
|
78
|
-
function parsePopulate(populate) {
|
|
79
|
-
if (!populate) return [];
|
|
80
|
-
if (typeof populate === "string") {
|
|
81
|
-
return populate.split(",").map((p) => p.trim());
|
|
82
|
-
}
|
|
83
|
-
if (Array.isArray(populate)) {
|
|
84
|
-
return populate.map((p) => typeof p === "string" ? p.trim() : p);
|
|
85
|
-
}
|
|
86
|
-
return [populate];
|
|
87
|
-
}
|
|
88
|
-
async function getById(Model, id, options = {}) {
|
|
89
|
-
const query = options.query ? Model.findOne({ _id: id, ...options.query }) : Model.findById(id);
|
|
90
|
-
if (options.select) query.select(options.select);
|
|
91
|
-
if (options.populate) query.populate(parsePopulate(options.populate));
|
|
92
|
-
if (options.lean) query.lean();
|
|
93
|
-
if (options.session) query.session(options.session);
|
|
94
|
-
const document = await query.exec();
|
|
95
|
-
if (!document && options.throwOnNotFound !== false) {
|
|
96
|
-
throw createError(404, "Document not found");
|
|
97
|
-
}
|
|
98
|
-
return document;
|
|
99
|
-
}
|
|
100
|
-
async function getByQuery(Model, query, options = {}) {
|
|
101
|
-
const mongoQuery = Model.findOne(query);
|
|
102
|
-
if (options.select) mongoQuery.select(options.select);
|
|
103
|
-
if (options.populate) mongoQuery.populate(parsePopulate(options.populate));
|
|
104
|
-
if (options.lean) mongoQuery.lean();
|
|
105
|
-
if (options.session) mongoQuery.session(options.session);
|
|
106
|
-
const document = await mongoQuery.exec();
|
|
107
|
-
if (!document && options.throwOnNotFound !== false) {
|
|
108
|
-
throw createError(404, "Document not found");
|
|
109
|
-
}
|
|
110
|
-
return document;
|
|
111
|
-
}
|
|
112
|
-
async function tryGetByQuery(Model, query, options = {}) {
|
|
113
|
-
return getByQuery(Model, query, { ...options, throwOnNotFound: false });
|
|
114
|
-
}
|
|
115
|
-
async function getAll(Model, query = {}, options = {}) {
|
|
116
|
-
let mongoQuery = Model.find(query);
|
|
117
|
-
if (options.select) mongoQuery = mongoQuery.select(options.select);
|
|
118
|
-
if (options.populate) mongoQuery = mongoQuery.populate(parsePopulate(options.populate));
|
|
119
|
-
if (options.sort) mongoQuery = mongoQuery.sort(options.sort);
|
|
120
|
-
if (options.limit) mongoQuery = mongoQuery.limit(options.limit);
|
|
121
|
-
if (options.skip) mongoQuery = mongoQuery.skip(options.skip);
|
|
122
|
-
mongoQuery = mongoQuery.lean(options.lean !== false);
|
|
123
|
-
if (options.session) mongoQuery = mongoQuery.session(options.session);
|
|
124
|
-
return mongoQuery.exec();
|
|
125
|
-
}
|
|
126
|
-
async function getOrCreate(Model, query, createData, options = {}) {
|
|
127
|
-
return Model.findOneAndUpdate(
|
|
128
|
-
query,
|
|
129
|
-
{ $setOnInsert: createData },
|
|
130
|
-
{
|
|
131
|
-
upsert: true,
|
|
132
|
-
new: true,
|
|
133
|
-
runValidators: true,
|
|
134
|
-
session: options.session,
|
|
135
|
-
...options.updatePipeline !== void 0 ? { updatePipeline: options.updatePipeline } : {}
|
|
136
|
-
}
|
|
137
|
-
);
|
|
138
|
-
}
|
|
139
|
-
async function count(Model, query = {}, options = {}) {
|
|
140
|
-
return Model.countDocuments(query).session(options.session ?? null);
|
|
141
|
-
}
|
|
142
|
-
async function exists(Model, query, options = {}) {
|
|
143
|
-
return Model.exists(query).session(options.session ?? null);
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
// src/actions/update.ts
|
|
147
|
-
var update_exports = {};
|
|
148
|
-
__export(update_exports, {
|
|
149
|
-
increment: () => increment,
|
|
150
|
-
pullFromArray: () => pullFromArray,
|
|
151
|
-
pushToArray: () => pushToArray,
|
|
152
|
-
update: () => update,
|
|
153
|
-
updateByQuery: () => updateByQuery,
|
|
154
|
-
updateMany: () => updateMany,
|
|
155
|
-
updateWithConstraints: () => updateWithConstraints,
|
|
156
|
-
updateWithValidation: () => updateWithValidation
|
|
157
|
-
});
|
|
158
|
-
function parsePopulate2(populate) {
|
|
159
|
-
if (!populate) return [];
|
|
160
|
-
if (typeof populate === "string") {
|
|
161
|
-
return populate.split(",").map((p) => p.trim());
|
|
162
|
-
}
|
|
163
|
-
if (Array.isArray(populate)) {
|
|
164
|
-
return populate.map((p) => typeof p === "string" ? p.trim() : p);
|
|
165
|
-
}
|
|
166
|
-
return [populate];
|
|
167
|
-
}
|
|
168
|
-
async function update(Model, id, data, options = {}) {
|
|
169
|
-
const document = await Model.findByIdAndUpdate(id, data, {
|
|
170
|
-
new: true,
|
|
171
|
-
runValidators: true,
|
|
172
|
-
session: options.session,
|
|
173
|
-
...options.updatePipeline !== void 0 ? { updatePipeline: options.updatePipeline } : {}
|
|
174
|
-
}).select(options.select || "").populate(parsePopulate2(options.populate)).lean(options.lean ?? false);
|
|
175
|
-
if (!document) {
|
|
176
|
-
throw createError(404, "Document not found");
|
|
177
|
-
}
|
|
178
|
-
return document;
|
|
179
|
-
}
|
|
180
|
-
async function updateWithConstraints(Model, id, data, constraints = {}, options = {}) {
|
|
181
|
-
const query = { _id: id, ...constraints };
|
|
182
|
-
const document = await Model.findOneAndUpdate(query, data, {
|
|
183
|
-
new: true,
|
|
184
|
-
runValidators: true,
|
|
185
|
-
session: options.session,
|
|
186
|
-
...options.updatePipeline !== void 0 ? { updatePipeline: options.updatePipeline } : {}
|
|
187
|
-
}).select(options.select || "").populate(parsePopulate2(options.populate)).lean(options.lean ?? false);
|
|
188
|
-
return document;
|
|
189
|
-
}
|
|
190
|
-
async function updateWithValidation(Model, id, data, validationOptions = {}, options = {}) {
|
|
191
|
-
const { buildConstraints, validateUpdate } = validationOptions;
|
|
192
|
-
if (buildConstraints) {
|
|
193
|
-
const constraints = buildConstraints(data);
|
|
194
|
-
const document = await updateWithConstraints(Model, id, data, constraints, options);
|
|
195
|
-
if (document) {
|
|
196
|
-
return { success: true, data: document };
|
|
197
|
-
}
|
|
198
|
-
}
|
|
199
|
-
const existing = await Model.findById(id).select(options.select || "").lean();
|
|
200
|
-
if (!existing) {
|
|
201
|
-
return {
|
|
202
|
-
success: false,
|
|
203
|
-
error: {
|
|
204
|
-
code: 404,
|
|
205
|
-
message: "Document not found"
|
|
206
|
-
}
|
|
207
|
-
};
|
|
208
|
-
}
|
|
209
|
-
if (validateUpdate) {
|
|
210
|
-
const validation = validateUpdate(existing, data);
|
|
211
|
-
if (!validation.valid) {
|
|
212
|
-
return {
|
|
213
|
-
success: false,
|
|
214
|
-
error: {
|
|
215
|
-
code: 403,
|
|
216
|
-
message: validation.message || "Update not allowed",
|
|
217
|
-
violations: validation.violations
|
|
218
|
-
}
|
|
219
|
-
};
|
|
220
|
-
}
|
|
221
|
-
}
|
|
222
|
-
const updated = await update(Model, id, data, options);
|
|
223
|
-
return { success: true, data: updated };
|
|
224
|
-
}
|
|
225
|
-
async function updateMany(Model, query, data, options = {}) {
|
|
226
|
-
const result = await Model.updateMany(query, data, {
|
|
227
|
-
runValidators: true,
|
|
228
|
-
session: options.session,
|
|
229
|
-
...options.updatePipeline !== void 0 ? { updatePipeline: options.updatePipeline } : {}
|
|
230
|
-
});
|
|
231
|
-
return {
|
|
232
|
-
matchedCount: result.matchedCount,
|
|
233
|
-
modifiedCount: result.modifiedCount
|
|
234
|
-
};
|
|
235
|
-
}
|
|
236
|
-
async function updateByQuery(Model, query, data, options = {}) {
|
|
237
|
-
const document = await Model.findOneAndUpdate(query, data, {
|
|
238
|
-
new: true,
|
|
239
|
-
runValidators: true,
|
|
240
|
-
session: options.session,
|
|
241
|
-
...options.updatePipeline !== void 0 ? { updatePipeline: options.updatePipeline } : {}
|
|
242
|
-
}).select(options.select || "").populate(parsePopulate2(options.populate)).lean(options.lean ?? false);
|
|
243
|
-
if (!document && options.throwOnNotFound !== false) {
|
|
244
|
-
throw createError(404, "Document not found");
|
|
245
|
-
}
|
|
246
|
-
return document;
|
|
247
|
-
}
|
|
248
|
-
async function increment(Model, id, field, value = 1, options = {}) {
|
|
249
|
-
return update(Model, id, { $inc: { [field]: value } }, options);
|
|
250
|
-
}
|
|
251
|
-
async function pushToArray(Model, id, field, value, options = {}) {
|
|
252
|
-
return update(Model, id, { $push: { [field]: value } }, options);
|
|
253
|
-
}
|
|
254
|
-
async function pullFromArray(Model, id, field, value, options = {}) {
|
|
255
|
-
return update(Model, id, { $pull: { [field]: value } }, options);
|
|
256
|
-
}
|
|
257
|
-
|
|
258
|
-
// src/actions/delete.ts
|
|
259
|
-
var delete_exports = {};
|
|
260
|
-
__export(delete_exports, {
|
|
261
|
-
deleteById: () => deleteById,
|
|
262
|
-
deleteByQuery: () => deleteByQuery,
|
|
263
|
-
deleteMany: () => deleteMany,
|
|
264
|
-
restore: () => restore,
|
|
265
|
-
softDelete: () => softDelete
|
|
266
|
-
});
|
|
267
|
-
async function deleteById(Model, id, options = {}) {
|
|
268
|
-
const document = await Model.findByIdAndDelete(id).session(options.session ?? null);
|
|
269
|
-
if (!document) {
|
|
270
|
-
throw createError(404, "Document not found");
|
|
271
|
-
}
|
|
272
|
-
return { success: true, message: "Deleted successfully" };
|
|
273
|
-
}
|
|
274
|
-
async function deleteMany(Model, query, options = {}) {
|
|
275
|
-
const result = await Model.deleteMany(query).session(options.session ?? null);
|
|
276
|
-
return {
|
|
277
|
-
success: true,
|
|
278
|
-
count: result.deletedCount,
|
|
279
|
-
message: "Deleted successfully"
|
|
280
|
-
};
|
|
281
|
-
}
|
|
282
|
-
async function deleteByQuery(Model, query, options = {}) {
|
|
283
|
-
const document = await Model.findOneAndDelete(query).session(options.session ?? null);
|
|
284
|
-
if (!document && options.throwOnNotFound !== false) {
|
|
285
|
-
throw createError(404, "Document not found");
|
|
286
|
-
}
|
|
287
|
-
return { success: true, message: "Deleted successfully" };
|
|
288
|
-
}
|
|
289
|
-
async function softDelete(Model, id, options = {}) {
|
|
290
|
-
const document = await Model.findByIdAndUpdate(
|
|
291
|
-
id,
|
|
292
|
-
{
|
|
293
|
-
deleted: true,
|
|
294
|
-
deletedAt: /* @__PURE__ */ new Date(),
|
|
295
|
-
deletedBy: options.userId
|
|
296
|
-
},
|
|
297
|
-
{ new: true, session: options.session }
|
|
298
|
-
);
|
|
299
|
-
if (!document) {
|
|
300
|
-
throw createError(404, "Document not found");
|
|
301
|
-
}
|
|
302
|
-
return { success: true, message: "Soft deleted successfully" };
|
|
303
|
-
}
|
|
304
|
-
async function restore(Model, id, options = {}) {
|
|
305
|
-
const document = await Model.findByIdAndUpdate(
|
|
306
|
-
id,
|
|
307
|
-
{
|
|
308
|
-
deleted: false,
|
|
309
|
-
deletedAt: null,
|
|
310
|
-
deletedBy: null
|
|
311
|
-
},
|
|
312
|
-
{ new: true, session: options.session }
|
|
313
|
-
);
|
|
314
|
-
if (!document) {
|
|
315
|
-
throw createError(404, "Document not found");
|
|
316
|
-
}
|
|
317
|
-
return { success: true, message: "Restored successfully" };
|
|
318
|
-
}
|
|
319
|
-
|
|
320
|
-
// src/actions/aggregate.ts
|
|
321
|
-
var aggregate_exports = {};
|
|
322
|
-
__export(aggregate_exports, {
|
|
323
|
-
aggregate: () => aggregate,
|
|
324
|
-
aggregatePaginate: () => aggregatePaginate,
|
|
325
|
-
average: () => average,
|
|
326
|
-
countBy: () => countBy,
|
|
327
|
-
distinct: () => distinct,
|
|
328
|
-
facet: () => facet,
|
|
329
|
-
groupBy: () => groupBy,
|
|
330
|
-
lookup: () => lookup,
|
|
331
|
-
minMax: () => minMax,
|
|
332
|
-
sum: () => sum,
|
|
333
|
-
unwind: () => unwind
|
|
334
|
-
});
|
|
335
|
-
async function aggregate(Model, pipeline, options = {}) {
|
|
336
|
-
const aggregation = Model.aggregate(pipeline);
|
|
337
|
-
if (options.session) {
|
|
338
|
-
aggregation.session(options.session);
|
|
339
|
-
}
|
|
340
|
-
return aggregation.exec();
|
|
341
|
-
}
|
|
342
|
-
async function aggregatePaginate(Model, pipeline, options = {}) {
|
|
343
|
-
const page = parseInt(String(options.page || 1), 10);
|
|
344
|
-
const limit = parseInt(String(options.limit || 10), 10);
|
|
345
|
-
const skip = (page - 1) * limit;
|
|
346
|
-
const SAFE_LIMIT = 1e3;
|
|
347
|
-
if (limit > SAFE_LIMIT) {
|
|
348
|
-
console.warn(
|
|
349
|
-
`[mongokit] Large aggregation limit (${limit}). $facet results must be <16MB. Consider using Repository.aggregatePaginate() for safer handling of large datasets.`
|
|
350
|
-
);
|
|
351
|
-
}
|
|
352
|
-
const facetPipeline = [
|
|
353
|
-
...pipeline,
|
|
354
|
-
{
|
|
355
|
-
$facet: {
|
|
356
|
-
docs: [{ $skip: skip }, { $limit: limit }],
|
|
357
|
-
total: [{ $count: "count" }]
|
|
358
|
-
}
|
|
359
|
-
}
|
|
360
|
-
];
|
|
361
|
-
const aggregation = Model.aggregate(facetPipeline);
|
|
362
|
-
if (options.session) {
|
|
363
|
-
aggregation.session(options.session);
|
|
364
|
-
}
|
|
365
|
-
const [result] = await aggregation.exec();
|
|
366
|
-
const docs = result.docs || [];
|
|
367
|
-
const total = result.total[0]?.count || 0;
|
|
368
|
-
const pages = Math.ceil(total / limit);
|
|
369
|
-
return {
|
|
370
|
-
docs,
|
|
371
|
-
total,
|
|
372
|
-
page,
|
|
373
|
-
limit,
|
|
374
|
-
pages,
|
|
375
|
-
hasNext: page < pages,
|
|
376
|
-
hasPrev: page > 1
|
|
377
|
-
};
|
|
378
|
-
}
|
|
379
|
-
async function groupBy(Model, field, options = {}) {
|
|
380
|
-
const pipeline = [
|
|
381
|
-
{ $group: { _id: `$${field}`, count: { $sum: 1 } } },
|
|
382
|
-
{ $sort: { count: -1 } }
|
|
383
|
-
];
|
|
384
|
-
if (options.limit) {
|
|
385
|
-
pipeline.push({ $limit: options.limit });
|
|
386
|
-
}
|
|
387
|
-
return aggregate(Model, pipeline, options);
|
|
388
|
-
}
|
|
389
|
-
async function countBy(Model, field, query = {}, options = {}) {
|
|
390
|
-
const pipeline = [];
|
|
391
|
-
if (Object.keys(query).length > 0) {
|
|
392
|
-
pipeline.push({ $match: query });
|
|
393
|
-
}
|
|
394
|
-
pipeline.push(
|
|
395
|
-
{ $group: { _id: `$${field}`, count: { $sum: 1 } } },
|
|
396
|
-
{ $sort: { count: -1 } }
|
|
397
|
-
);
|
|
398
|
-
return aggregate(Model, pipeline, options);
|
|
399
|
-
}
|
|
400
|
-
async function lookup(Model, lookupOptions) {
|
|
401
|
-
const { from, localField, foreignField, as, pipeline = [], query = {}, options = {} } = lookupOptions;
|
|
402
|
-
const aggPipeline = [];
|
|
403
|
-
if (Object.keys(query).length > 0) {
|
|
404
|
-
aggPipeline.push({ $match: query });
|
|
405
|
-
}
|
|
406
|
-
aggPipeline.push({
|
|
407
|
-
$lookup: {
|
|
408
|
-
from,
|
|
409
|
-
localField,
|
|
410
|
-
foreignField,
|
|
411
|
-
as,
|
|
412
|
-
...pipeline.length > 0 ? { pipeline } : {}
|
|
413
|
-
}
|
|
414
|
-
});
|
|
415
|
-
return aggregate(Model, aggPipeline, options);
|
|
416
|
-
}
|
|
417
|
-
async function unwind(Model, field, options = {}) {
|
|
418
|
-
const pipeline = [
|
|
419
|
-
{
|
|
420
|
-
$unwind: {
|
|
421
|
-
path: `$${field}`,
|
|
422
|
-
preserveNullAndEmptyArrays: options.preserveEmpty !== false
|
|
423
|
-
}
|
|
424
|
-
}
|
|
425
|
-
];
|
|
426
|
-
return aggregate(Model, pipeline, { session: options.session });
|
|
427
|
-
}
|
|
428
|
-
async function facet(Model, facets, options = {}) {
|
|
429
|
-
const pipeline = [{ $facet: facets }];
|
|
430
|
-
return aggregate(Model, pipeline, options);
|
|
431
|
-
}
|
|
432
|
-
async function distinct(Model, field, query = {}, options = {}) {
|
|
433
|
-
return Model.distinct(field, query).session(options.session ?? null);
|
|
434
|
-
}
|
|
435
|
-
async function sum(Model, field, query = {}, options = {}) {
|
|
436
|
-
const pipeline = [];
|
|
437
|
-
if (Object.keys(query).length > 0) {
|
|
438
|
-
pipeline.push({ $match: query });
|
|
439
|
-
}
|
|
440
|
-
pipeline.push({
|
|
441
|
-
$group: {
|
|
442
|
-
_id: null,
|
|
443
|
-
total: { $sum: `$${field}` }
|
|
444
|
-
}
|
|
445
|
-
});
|
|
446
|
-
const result = await aggregate(Model, pipeline, options);
|
|
447
|
-
return result[0]?.total || 0;
|
|
448
|
-
}
|
|
449
|
-
async function average(Model, field, query = {}, options = {}) {
|
|
450
|
-
const pipeline = [];
|
|
451
|
-
if (Object.keys(query).length > 0) {
|
|
452
|
-
pipeline.push({ $match: query });
|
|
453
|
-
}
|
|
454
|
-
pipeline.push({
|
|
455
|
-
$group: {
|
|
456
|
-
_id: null,
|
|
457
|
-
average: { $avg: `$${field}` }
|
|
458
|
-
}
|
|
459
|
-
});
|
|
460
|
-
const result = await aggregate(Model, pipeline, options);
|
|
461
|
-
return result[0]?.average || 0;
|
|
462
|
-
}
|
|
463
|
-
async function minMax(Model, field, query = {}, options = {}) {
|
|
464
|
-
const pipeline = [];
|
|
465
|
-
if (Object.keys(query).length > 0) {
|
|
466
|
-
pipeline.push({ $match: query });
|
|
467
|
-
}
|
|
468
|
-
pipeline.push({
|
|
469
|
-
$group: {
|
|
470
|
-
_id: null,
|
|
471
|
-
min: { $min: `$${field}` },
|
|
472
|
-
max: { $max: `$${field}` }
|
|
473
|
-
}
|
|
474
|
-
});
|
|
475
|
-
const result = await aggregate(Model, pipeline, options);
|
|
476
|
-
return result[0] || { min: null, max: null };
|
|
477
|
-
}
|
|
478
|
-
function encodeCursor(doc, primaryField, sort, version = 1) {
|
|
479
|
-
const primaryValue = doc[primaryField];
|
|
480
|
-
const idValue = doc._id;
|
|
481
|
-
const payload = {
|
|
482
|
-
v: serializeValue(primaryValue),
|
|
483
|
-
t: getValueType(primaryValue),
|
|
484
|
-
id: serializeValue(idValue),
|
|
485
|
-
idType: getValueType(idValue),
|
|
486
|
-
sort,
|
|
487
|
-
ver: version
|
|
488
|
-
};
|
|
489
|
-
return Buffer.from(JSON.stringify(payload)).toString("base64");
|
|
490
|
-
}
|
|
491
|
-
function decodeCursor(token) {
|
|
492
|
-
try {
|
|
493
|
-
const json = Buffer.from(token, "base64").toString("utf-8");
|
|
494
|
-
const payload = JSON.parse(json);
|
|
495
|
-
return {
|
|
496
|
-
value: rehydrateValue(payload.v, payload.t),
|
|
497
|
-
id: rehydrateValue(payload.id, payload.idType),
|
|
498
|
-
sort: payload.sort,
|
|
499
|
-
version: payload.ver
|
|
500
|
-
};
|
|
501
|
-
} catch {
|
|
502
|
-
throw new Error("Invalid cursor token");
|
|
503
|
-
}
|
|
504
|
-
}
|
|
505
|
-
function validateCursorSort(cursorSort, currentSort) {
|
|
506
|
-
const cursorSortStr = JSON.stringify(cursorSort);
|
|
507
|
-
const currentSortStr = JSON.stringify(currentSort);
|
|
508
|
-
if (cursorSortStr !== currentSortStr) {
|
|
509
|
-
throw new Error("Cursor sort does not match current query sort");
|
|
510
|
-
}
|
|
511
|
-
}
|
|
512
|
-
function validateCursorVersion(cursorVersion, expectedVersion) {
|
|
513
|
-
if (cursorVersion !== expectedVersion) {
|
|
514
|
-
throw new Error(`Cursor version ${cursorVersion} does not match expected version ${expectedVersion}`);
|
|
515
|
-
}
|
|
516
|
-
}
|
|
517
|
-
function serializeValue(value) {
|
|
518
|
-
if (value instanceof Date) return value.toISOString();
|
|
519
|
-
if (value instanceof mongoose__default.default.Types.ObjectId) return value.toString();
|
|
520
|
-
return value;
|
|
521
|
-
}
|
|
522
|
-
function getValueType(value) {
|
|
523
|
-
if (value instanceof Date) return "date";
|
|
524
|
-
if (value instanceof mongoose__default.default.Types.ObjectId) return "objectid";
|
|
525
|
-
if (typeof value === "boolean") return "boolean";
|
|
526
|
-
if (typeof value === "number") return "number";
|
|
527
|
-
if (typeof value === "string") return "string";
|
|
528
|
-
return "unknown";
|
|
529
|
-
}
|
|
530
|
-
function rehydrateValue(serialized, type) {
|
|
531
|
-
switch (type) {
|
|
532
|
-
case "date":
|
|
533
|
-
return new Date(serialized);
|
|
534
|
-
case "objectid":
|
|
535
|
-
return new mongoose__default.default.Types.ObjectId(serialized);
|
|
536
|
-
case "boolean":
|
|
537
|
-
return Boolean(serialized);
|
|
538
|
-
case "number":
|
|
539
|
-
return Number(serialized);
|
|
540
|
-
default:
|
|
541
|
-
return serialized;
|
|
542
|
-
}
|
|
543
|
-
}
|
|
544
|
-
|
|
545
|
-
// src/pagination/utils/sort.ts
|
|
546
|
-
function normalizeSort(sort) {
|
|
547
|
-
const normalized = {};
|
|
548
|
-
Object.keys(sort).forEach((key) => {
|
|
549
|
-
if (key !== "_id") normalized[key] = sort[key];
|
|
550
|
-
});
|
|
551
|
-
if (sort._id !== void 0) {
|
|
552
|
-
normalized._id = sort._id;
|
|
553
|
-
}
|
|
554
|
-
return normalized;
|
|
555
|
-
}
|
|
556
|
-
function validateKeysetSort(sort) {
|
|
557
|
-
const keys = Object.keys(sort);
|
|
558
|
-
if (keys.length === 1 && keys[0] !== "_id") {
|
|
559
|
-
const field = keys[0];
|
|
560
|
-
const direction = sort[field];
|
|
561
|
-
return normalizeSort({ [field]: direction, _id: direction });
|
|
562
|
-
}
|
|
563
|
-
if (keys.length === 1 && keys[0] === "_id") {
|
|
564
|
-
return normalizeSort(sort);
|
|
565
|
-
}
|
|
566
|
-
if (keys.length === 2) {
|
|
567
|
-
if (!keys.includes("_id")) {
|
|
568
|
-
throw new Error("Keyset pagination requires _id as tie-breaker");
|
|
569
|
-
}
|
|
570
|
-
const primaryField = keys.find((k) => k !== "_id");
|
|
571
|
-
const primaryDirection = sort[primaryField];
|
|
572
|
-
const idDirection = sort._id;
|
|
573
|
-
if (primaryDirection !== idDirection) {
|
|
574
|
-
throw new Error("_id direction must match primary field direction");
|
|
575
|
-
}
|
|
576
|
-
return normalizeSort(sort);
|
|
577
|
-
}
|
|
578
|
-
throw new Error("Keyset pagination only supports single field + _id");
|
|
579
|
-
}
|
|
580
|
-
function getPrimaryField(sort) {
|
|
581
|
-
const keys = Object.keys(sort);
|
|
582
|
-
return keys.find((k) => k !== "_id") || "_id";
|
|
583
|
-
}
|
|
584
|
-
|
|
585
|
-
// src/pagination/utils/filter.ts
|
|
586
|
-
function buildKeysetFilter(baseFilters, sort, cursorValue, cursorId) {
|
|
587
|
-
const primaryField = Object.keys(sort).find((k) => k !== "_id") || "_id";
|
|
588
|
-
const direction = sort[primaryField];
|
|
589
|
-
const operator = direction === 1 ? "$gt" : "$lt";
|
|
590
|
-
return {
|
|
591
|
-
...baseFilters,
|
|
592
|
-
$or: [
|
|
593
|
-
{ [primaryField]: { [operator]: cursorValue } },
|
|
594
|
-
{
|
|
595
|
-
[primaryField]: cursorValue,
|
|
596
|
-
_id: { [operator]: cursorId }
|
|
597
|
-
}
|
|
598
|
-
]
|
|
599
|
-
};
|
|
600
|
-
}
|
|
601
|
-
|
|
602
|
-
// src/pagination/utils/limits.ts
|
|
603
|
-
function validateLimit(limit, config) {
|
|
604
|
-
const parsed = Number(limit);
|
|
605
|
-
if (!Number.isFinite(parsed) || parsed < 1) {
|
|
606
|
-
return config.defaultLimit || 10;
|
|
607
|
-
}
|
|
608
|
-
return Math.min(Math.floor(parsed), config.maxLimit || 100);
|
|
609
|
-
}
|
|
610
|
-
function validatePage(page, config) {
|
|
611
|
-
const parsed = Number(page);
|
|
612
|
-
if (!Number.isFinite(parsed) || parsed < 1) {
|
|
613
|
-
return 1;
|
|
614
|
-
}
|
|
615
|
-
const sanitized = Math.floor(parsed);
|
|
616
|
-
if (sanitized > (config.maxPage || 1e4)) {
|
|
617
|
-
throw new Error(`Page ${sanitized} exceeds maximum ${config.maxPage || 1e4}`);
|
|
618
|
-
}
|
|
619
|
-
return sanitized;
|
|
620
|
-
}
|
|
621
|
-
function shouldWarnDeepPagination(page, threshold) {
|
|
622
|
-
return page > threshold;
|
|
623
|
-
}
|
|
624
|
-
function calculateSkip(page, limit) {
|
|
625
|
-
return (page - 1) * limit;
|
|
626
|
-
}
|
|
627
|
-
function calculateTotalPages(total, limit) {
|
|
628
|
-
return Math.ceil(total / limit);
|
|
629
|
-
}
|
|
630
|
-
|
|
631
|
-
// src/pagination/PaginationEngine.ts
|
|
632
|
-
var PaginationEngine = class {
|
|
633
|
-
Model;
|
|
634
|
-
config;
|
|
635
|
-
/**
|
|
636
|
-
* Create a new pagination engine
|
|
637
|
-
*
|
|
638
|
-
* @param Model - Mongoose model to paginate
|
|
639
|
-
* @param config - Pagination configuration
|
|
640
|
-
*/
|
|
641
|
-
constructor(Model, config = {}) {
|
|
642
|
-
this.Model = Model;
|
|
643
|
-
this.config = {
|
|
644
|
-
defaultLimit: config.defaultLimit || 10,
|
|
645
|
-
maxLimit: config.maxLimit || 100,
|
|
646
|
-
maxPage: config.maxPage || 1e4,
|
|
647
|
-
deepPageThreshold: config.deepPageThreshold || 100,
|
|
648
|
-
cursorVersion: config.cursorVersion || 1,
|
|
649
|
-
useEstimatedCount: config.useEstimatedCount || false
|
|
650
|
-
};
|
|
651
|
-
}
|
|
652
|
-
/**
|
|
653
|
-
* Offset-based pagination using skip/limit
|
|
654
|
-
* Best for small datasets and when users need random page access
|
|
655
|
-
* O(n) performance - slower for deep pages
|
|
656
|
-
*
|
|
657
|
-
* @param options - Pagination options
|
|
658
|
-
* @returns Pagination result with total count
|
|
659
|
-
*
|
|
660
|
-
* @example
|
|
661
|
-
* const result = await engine.paginate({
|
|
662
|
-
* filters: { status: 'active' },
|
|
663
|
-
* sort: { createdAt: -1 },
|
|
664
|
-
* page: 1,
|
|
665
|
-
* limit: 20
|
|
666
|
-
* });
|
|
667
|
-
* console.log(result.docs, result.total, result.hasNext);
|
|
668
|
-
*/
|
|
669
|
-
async paginate(options = {}) {
|
|
670
|
-
const {
|
|
671
|
-
filters = {},
|
|
672
|
-
sort = { _id: -1 },
|
|
673
|
-
page = 1,
|
|
674
|
-
limit = this.config.defaultLimit,
|
|
675
|
-
select,
|
|
676
|
-
populate = [],
|
|
677
|
-
lean = true,
|
|
678
|
-
session
|
|
679
|
-
} = options;
|
|
680
|
-
const sanitizedPage = validatePage(page, this.config);
|
|
681
|
-
const sanitizedLimit = validateLimit(limit, this.config);
|
|
682
|
-
const skip = calculateSkip(sanitizedPage, sanitizedLimit);
|
|
683
|
-
let query = this.Model.find(filters);
|
|
684
|
-
if (select) query = query.select(select);
|
|
685
|
-
if (populate && (Array.isArray(populate) ? populate.length : populate)) {
|
|
686
|
-
query = query.populate(populate);
|
|
687
|
-
}
|
|
688
|
-
query = query.sort(sort).skip(skip).limit(sanitizedLimit).lean(lean);
|
|
689
|
-
if (session) query = query.session(session);
|
|
690
|
-
const hasFilters = Object.keys(filters).length > 0;
|
|
691
|
-
const useEstimated = this.config.useEstimatedCount && !hasFilters;
|
|
692
|
-
const [docs, total] = await Promise.all([
|
|
693
|
-
query.exec(),
|
|
694
|
-
useEstimated ? this.Model.estimatedDocumentCount() : this.Model.countDocuments(filters).session(session ?? null)
|
|
695
|
-
]);
|
|
696
|
-
const totalPages = calculateTotalPages(total, sanitizedLimit);
|
|
697
|
-
const warning = shouldWarnDeepPagination(sanitizedPage, this.config.deepPageThreshold) ? `Deep pagination (page ${sanitizedPage}). Consider getAll({ after, sort, limit }) for better performance.` : void 0;
|
|
698
|
-
return {
|
|
699
|
-
method: "offset",
|
|
700
|
-
docs,
|
|
701
|
-
page: sanitizedPage,
|
|
702
|
-
limit: sanitizedLimit,
|
|
703
|
-
total,
|
|
704
|
-
pages: totalPages,
|
|
705
|
-
hasNext: sanitizedPage < totalPages,
|
|
706
|
-
hasPrev: sanitizedPage > 1,
|
|
707
|
-
...warning && { warning }
|
|
708
|
-
};
|
|
709
|
-
}
|
|
710
|
-
/**
|
|
711
|
-
* Keyset (cursor-based) pagination for high-performance streaming
|
|
712
|
-
* Best for large datasets, infinite scroll, real-time feeds
|
|
713
|
-
* O(1) performance - consistent speed regardless of position
|
|
714
|
-
*
|
|
715
|
-
* @param options - Pagination options (sort is required)
|
|
716
|
-
* @returns Pagination result with next cursor
|
|
717
|
-
*
|
|
718
|
-
* @example
|
|
719
|
-
* // First page
|
|
720
|
-
* const page1 = await engine.stream({
|
|
721
|
-
* sort: { createdAt: -1 },
|
|
722
|
-
* limit: 20
|
|
723
|
-
* });
|
|
724
|
-
*
|
|
725
|
-
* // Next page using cursor
|
|
726
|
-
* const page2 = await engine.stream({
|
|
727
|
-
* sort: { createdAt: -1 },
|
|
728
|
-
* after: page1.next,
|
|
729
|
-
* limit: 20
|
|
730
|
-
* });
|
|
731
|
-
*/
|
|
732
|
-
async stream(options) {
|
|
733
|
-
const {
|
|
734
|
-
filters = {},
|
|
735
|
-
sort,
|
|
736
|
-
after,
|
|
737
|
-
limit = this.config.defaultLimit,
|
|
738
|
-
select,
|
|
739
|
-
populate = [],
|
|
740
|
-
lean = true,
|
|
741
|
-
session
|
|
742
|
-
} = options;
|
|
743
|
-
if (!sort) {
|
|
744
|
-
throw createError(400, "sort is required for keyset pagination");
|
|
745
|
-
}
|
|
746
|
-
const sanitizedLimit = validateLimit(limit, this.config);
|
|
747
|
-
const normalizedSort = validateKeysetSort(sort);
|
|
748
|
-
let query = { ...filters };
|
|
749
|
-
if (after) {
|
|
750
|
-
const cursor = decodeCursor(after);
|
|
751
|
-
validateCursorVersion(cursor.version, this.config.cursorVersion);
|
|
752
|
-
validateCursorSort(cursor.sort, normalizedSort);
|
|
753
|
-
query = buildKeysetFilter(query, normalizedSort, cursor.value, cursor.id);
|
|
754
|
-
}
|
|
755
|
-
let mongoQuery = this.Model.find(query);
|
|
756
|
-
if (select) mongoQuery = mongoQuery.select(select);
|
|
757
|
-
if (populate && (Array.isArray(populate) ? populate.length : populate)) {
|
|
758
|
-
mongoQuery = mongoQuery.populate(populate);
|
|
759
|
-
}
|
|
760
|
-
mongoQuery = mongoQuery.sort(normalizedSort).limit(sanitizedLimit + 1).lean(lean);
|
|
761
|
-
if (session) mongoQuery = mongoQuery.session(session);
|
|
762
|
-
const docs = await mongoQuery.exec();
|
|
763
|
-
const hasMore = docs.length > sanitizedLimit;
|
|
764
|
-
if (hasMore) docs.pop();
|
|
765
|
-
const primaryField = getPrimaryField(normalizedSort);
|
|
766
|
-
const nextCursor = hasMore && docs.length > 0 ? encodeCursor(docs[docs.length - 1], primaryField, normalizedSort, this.config.cursorVersion) : null;
|
|
767
|
-
return {
|
|
768
|
-
method: "keyset",
|
|
769
|
-
docs,
|
|
770
|
-
limit: sanitizedLimit,
|
|
771
|
-
hasMore,
|
|
772
|
-
next: nextCursor
|
|
773
|
-
};
|
|
774
|
-
}
|
|
775
|
-
/**
|
|
776
|
-
* Aggregate pipeline with pagination
|
|
777
|
-
* Best for complex queries requiring aggregation stages
|
|
778
|
-
* Uses $facet to combine results and count in single query
|
|
779
|
-
*
|
|
780
|
-
* @param options - Aggregation options
|
|
781
|
-
* @returns Pagination result with total count
|
|
782
|
-
*
|
|
783
|
-
* @example
|
|
784
|
-
* const result = await engine.aggregatePaginate({
|
|
785
|
-
* pipeline: [
|
|
786
|
-
* { $match: { status: 'active' } },
|
|
787
|
-
* { $group: { _id: '$category', count: { $sum: 1 } } },
|
|
788
|
-
* { $sort: { count: -1 } }
|
|
789
|
-
* ],
|
|
790
|
-
* page: 1,
|
|
791
|
-
* limit: 20
|
|
792
|
-
* });
|
|
793
|
-
*/
|
|
794
|
-
async aggregatePaginate(options = {}) {
|
|
795
|
-
const {
|
|
796
|
-
pipeline = [],
|
|
797
|
-
page = 1,
|
|
798
|
-
limit = this.config.defaultLimit,
|
|
799
|
-
session
|
|
800
|
-
} = options;
|
|
801
|
-
const sanitizedPage = validatePage(page, this.config);
|
|
802
|
-
const sanitizedLimit = validateLimit(limit, this.config);
|
|
803
|
-
const skip = calculateSkip(sanitizedPage, sanitizedLimit);
|
|
804
|
-
const facetPipeline = [
|
|
805
|
-
...pipeline,
|
|
806
|
-
{
|
|
807
|
-
$facet: {
|
|
808
|
-
docs: [{ $skip: skip }, { $limit: sanitizedLimit }],
|
|
809
|
-
total: [{ $count: "count" }]
|
|
810
|
-
}
|
|
811
|
-
}
|
|
812
|
-
];
|
|
813
|
-
const aggregation = this.Model.aggregate(facetPipeline);
|
|
814
|
-
if (session) aggregation.session(session);
|
|
815
|
-
const [result] = await aggregation.exec();
|
|
816
|
-
const docs = result.docs;
|
|
817
|
-
const total = result.total[0]?.count || 0;
|
|
818
|
-
const totalPages = calculateTotalPages(total, sanitizedLimit);
|
|
819
|
-
const warning = shouldWarnDeepPagination(sanitizedPage, this.config.deepPageThreshold) ? `Deep pagination in aggregate (page ${sanitizedPage}). Uses $skip internally.` : void 0;
|
|
820
|
-
return {
|
|
821
|
-
method: "aggregate",
|
|
822
|
-
docs,
|
|
823
|
-
page: sanitizedPage,
|
|
824
|
-
limit: sanitizedLimit,
|
|
825
|
-
total,
|
|
826
|
-
pages: totalPages,
|
|
827
|
-
hasNext: sanitizedPage < totalPages,
|
|
828
|
-
hasPrev: sanitizedPage > 1,
|
|
829
|
-
...warning && { warning }
|
|
830
|
-
};
|
|
831
|
-
}
|
|
832
|
-
};
|
|
833
|
-
|
|
834
|
-
// src/Repository.ts
|
|
835
|
-
var Repository = class {
|
|
836
|
-
Model;
|
|
837
|
-
model;
|
|
838
|
-
_hooks;
|
|
839
|
-
_pagination;
|
|
840
|
-
constructor(Model, plugins = [], paginationConfig = {}) {
|
|
841
|
-
this.Model = Model;
|
|
842
|
-
this.model = Model.modelName;
|
|
843
|
-
this._hooks = /* @__PURE__ */ new Map();
|
|
844
|
-
this._pagination = new PaginationEngine(Model, paginationConfig);
|
|
845
|
-
plugins.forEach((plugin) => this.use(plugin));
|
|
846
|
-
}
|
|
847
|
-
/**
|
|
848
|
-
* Register a plugin
|
|
849
|
-
*/
|
|
850
|
-
use(plugin) {
|
|
851
|
-
if (typeof plugin === "function") {
|
|
852
|
-
plugin(this);
|
|
853
|
-
} else if (plugin && typeof plugin.apply === "function") {
|
|
854
|
-
plugin.apply(this);
|
|
855
|
-
}
|
|
856
|
-
return this;
|
|
857
|
-
}
|
|
858
|
-
/**
|
|
859
|
-
* Register event listener
|
|
860
|
-
*/
|
|
861
|
-
on(event, listener) {
|
|
862
|
-
if (!this._hooks.has(event)) {
|
|
863
|
-
this._hooks.set(event, []);
|
|
864
|
-
}
|
|
865
|
-
this._hooks.get(event).push(listener);
|
|
866
|
-
return this;
|
|
867
|
-
}
|
|
868
|
-
/**
|
|
869
|
-
* Emit event
|
|
870
|
-
*/
|
|
871
|
-
emit(event, data) {
|
|
872
|
-
const listeners = this._hooks.get(event) || [];
|
|
873
|
-
listeners.forEach((listener) => listener(data));
|
|
874
|
-
}
|
|
875
|
-
/**
|
|
876
|
-
* Create single document
|
|
877
|
-
*/
|
|
878
|
-
async create(data, options = {}) {
|
|
879
|
-
const context = await this._buildContext("create", { data, ...options });
|
|
880
|
-
try {
|
|
881
|
-
const result = await create(this.Model, context.data || data, options);
|
|
882
|
-
this.emit("after:create", { context, result });
|
|
883
|
-
return result;
|
|
884
|
-
} catch (error) {
|
|
885
|
-
this.emit("error:create", { context, error });
|
|
886
|
-
throw this._handleError(error);
|
|
887
|
-
}
|
|
888
|
-
}
|
|
889
|
-
/**
|
|
890
|
-
* Create multiple documents
|
|
891
|
-
*/
|
|
892
|
-
async createMany(dataArray, options = {}) {
|
|
893
|
-
const context = await this._buildContext("createMany", { dataArray, ...options });
|
|
894
|
-
try {
|
|
895
|
-
const result = await createMany(this.Model, context.dataArray || dataArray, options);
|
|
896
|
-
this.emit("after:createMany", { context, result });
|
|
897
|
-
return result;
|
|
898
|
-
} catch (error) {
|
|
899
|
-
this.emit("error:createMany", { context, error });
|
|
900
|
-
throw this._handleError(error);
|
|
901
|
-
}
|
|
902
|
-
}
|
|
903
|
-
/**
|
|
904
|
-
* Get document by ID
|
|
905
|
-
*/
|
|
906
|
-
async getById(id, options = {}) {
|
|
907
|
-
const context = await this._buildContext("getById", { id, ...options });
|
|
908
|
-
if (context._cacheHit) {
|
|
909
|
-
return context._cachedResult;
|
|
910
|
-
}
|
|
911
|
-
const result = await getById(this.Model, id, context);
|
|
912
|
-
this.emit("after:getById", { context, result });
|
|
913
|
-
return result;
|
|
914
|
-
}
|
|
915
|
-
/**
|
|
916
|
-
* Get single document by query
|
|
917
|
-
*/
|
|
918
|
-
async getByQuery(query, options = {}) {
|
|
919
|
-
const context = await this._buildContext("getByQuery", { query, ...options });
|
|
920
|
-
if (context._cacheHit) {
|
|
921
|
-
return context._cachedResult;
|
|
922
|
-
}
|
|
923
|
-
const result = await getByQuery(this.Model, query, context);
|
|
924
|
-
this.emit("after:getByQuery", { context, result });
|
|
925
|
-
return result;
|
|
926
|
-
}
|
|
927
|
-
/**
|
|
928
|
-
* Unified pagination - auto-detects offset vs keyset based on params
|
|
929
|
-
*
|
|
930
|
-
* Auto-detection logic:
|
|
931
|
-
* - If params has 'cursor' or 'after' → uses keyset pagination (stream)
|
|
932
|
-
* - If params has 'pagination' or 'page' → uses offset pagination (paginate)
|
|
933
|
-
* - Else → defaults to offset pagination with page=1
|
|
934
|
-
*
|
|
935
|
-
* @example
|
|
936
|
-
* // Offset pagination (page-based)
|
|
937
|
-
* await repo.getAll({ page: 1, limit: 50, filters: { status: 'active' } });
|
|
938
|
-
* await repo.getAll({ pagination: { page: 2, limit: 20 } });
|
|
939
|
-
*
|
|
940
|
-
* // Keyset pagination (cursor-based)
|
|
941
|
-
* await repo.getAll({ cursor: 'eyJ2Ij...', limit: 50 });
|
|
942
|
-
* await repo.getAll({ after: 'eyJ2Ij...', sort: { createdAt: -1 } });
|
|
943
|
-
*
|
|
944
|
-
* // Simple query (defaults to page 1)
|
|
945
|
-
* await repo.getAll({ filters: { status: 'active' } });
|
|
946
|
-
*
|
|
947
|
-
* // Skip cache for fresh data
|
|
948
|
-
* await repo.getAll({ filters: { status: 'active' } }, { skipCache: true });
|
|
949
|
-
*/
|
|
950
|
-
async getAll(params = {}, options = {}) {
|
|
951
|
-
const context = await this._buildContext("getAll", { ...params, ...options });
|
|
952
|
-
if (context._cacheHit) {
|
|
953
|
-
return context._cachedResult;
|
|
954
|
-
}
|
|
955
|
-
const hasPageParam = params.page !== void 0 || params.pagination;
|
|
956
|
-
const hasCursorParam = "cursor" in params || "after" in params;
|
|
957
|
-
const hasExplicitSort = params.sort !== void 0;
|
|
958
|
-
const useKeyset = !hasPageParam && (hasCursorParam || hasExplicitSort);
|
|
959
|
-
const filters = params.filters || {};
|
|
960
|
-
const search = params.search;
|
|
961
|
-
const sort = params.sort || "-createdAt";
|
|
962
|
-
const limit = params.limit || params.pagination?.limit || this._pagination.config.defaultLimit;
|
|
963
|
-
let query = { ...filters };
|
|
964
|
-
if (search) query.$text = { $search: search };
|
|
965
|
-
const paginationOptions = {
|
|
966
|
-
filters: query,
|
|
967
|
-
sort: this._parseSort(sort),
|
|
968
|
-
limit,
|
|
969
|
-
populate: this._parsePopulate(context.populate || options.populate),
|
|
970
|
-
select: context.select || options.select,
|
|
971
|
-
lean: context.lean ?? options.lean ?? true,
|
|
972
|
-
session: options.session
|
|
973
|
-
};
|
|
974
|
-
let result;
|
|
975
|
-
if (useKeyset) {
|
|
976
|
-
result = await this._pagination.stream({
|
|
977
|
-
...paginationOptions,
|
|
978
|
-
sort: paginationOptions.sort,
|
|
979
|
-
// Required for keyset
|
|
980
|
-
after: params.cursor || params.after
|
|
981
|
-
});
|
|
982
|
-
} else {
|
|
983
|
-
const page = params.pagination?.page || params.page || 1;
|
|
984
|
-
result = await this._pagination.paginate({
|
|
985
|
-
...paginationOptions,
|
|
986
|
-
page
|
|
987
|
-
});
|
|
988
|
-
}
|
|
989
|
-
this.emit("after:getAll", { context, result });
|
|
990
|
-
return result;
|
|
991
|
-
}
|
|
992
|
-
/**
|
|
993
|
-
* Get or create document
|
|
994
|
-
*/
|
|
995
|
-
async getOrCreate(query, createData, options = {}) {
|
|
996
|
-
return getOrCreate(this.Model, query, createData, options);
|
|
997
|
-
}
|
|
998
|
-
/**
|
|
999
|
-
* Count documents
|
|
1000
|
-
*/
|
|
1001
|
-
async count(query = {}, options = {}) {
|
|
1002
|
-
return count(this.Model, query, options);
|
|
1003
|
-
}
|
|
1004
|
-
/**
|
|
1005
|
-
* Check if document exists
|
|
1006
|
-
*/
|
|
1007
|
-
async exists(query, options = {}) {
|
|
1008
|
-
return exists(this.Model, query, options);
|
|
1009
|
-
}
|
|
1010
|
-
/**
|
|
1011
|
-
* Update document by ID
|
|
1012
|
-
*/
|
|
1013
|
-
async update(id, data, options = {}) {
|
|
1014
|
-
const context = await this._buildContext("update", { id, data, ...options });
|
|
1015
|
-
try {
|
|
1016
|
-
const result = await update(this.Model, id, context.data || data, context);
|
|
1017
|
-
this.emit("after:update", { context, result });
|
|
1018
|
-
return result;
|
|
1019
|
-
} catch (error) {
|
|
1020
|
-
this.emit("error:update", { context, error });
|
|
1021
|
-
throw this._handleError(error);
|
|
1022
|
-
}
|
|
1023
|
-
}
|
|
1024
|
-
/**
|
|
1025
|
-
* Delete document by ID
|
|
1026
|
-
*/
|
|
1027
|
-
async delete(id, options = {}) {
|
|
1028
|
-
const context = await this._buildContext("delete", { id, ...options });
|
|
1029
|
-
try {
|
|
1030
|
-
if (context.softDeleted) {
|
|
1031
|
-
const result2 = { success: true, message: "Soft deleted successfully" };
|
|
1032
|
-
this.emit("after:delete", { context, result: result2 });
|
|
1033
|
-
return result2;
|
|
1034
|
-
}
|
|
1035
|
-
const result = await deleteById(this.Model, id, options);
|
|
1036
|
-
this.emit("after:delete", { context, result });
|
|
1037
|
-
return result;
|
|
1038
|
-
} catch (error) {
|
|
1039
|
-
this.emit("error:delete", { context, error });
|
|
1040
|
-
throw this._handleError(error);
|
|
1041
|
-
}
|
|
1042
|
-
}
|
|
1043
|
-
/**
|
|
1044
|
-
* Execute aggregation pipeline
|
|
1045
|
-
*/
|
|
1046
|
-
async aggregate(pipeline, options = {}) {
|
|
1047
|
-
return aggregate(this.Model, pipeline, options);
|
|
1048
|
-
}
|
|
1049
|
-
/**
|
|
1050
|
-
* Aggregate pipeline with pagination
|
|
1051
|
-
* Best for: Complex queries, grouping, joins
|
|
1052
|
-
*/
|
|
1053
|
-
async aggregatePaginate(options = {}) {
|
|
1054
|
-
const context = await this._buildContext("aggregatePaginate", options);
|
|
1055
|
-
return this._pagination.aggregatePaginate(context);
|
|
1056
|
-
}
|
|
1057
|
-
/**
|
|
1058
|
-
* Get distinct values
|
|
1059
|
-
*/
|
|
1060
|
-
async distinct(field, query = {}, options = {}) {
|
|
1061
|
-
return distinct(this.Model, field, query, options);
|
|
1062
|
-
}
|
|
1063
|
-
/**
|
|
1064
|
-
* Execute callback within a transaction
|
|
1065
|
-
*/
|
|
1066
|
-
async withTransaction(callback) {
|
|
1067
|
-
const session = await mongoose__default.default.startSession();
|
|
1068
|
-
session.startTransaction();
|
|
1069
|
-
try {
|
|
1070
|
-
const result = await callback(session);
|
|
1071
|
-
await session.commitTransaction();
|
|
1072
|
-
return result;
|
|
1073
|
-
} catch (error) {
|
|
1074
|
-
await session.abortTransaction();
|
|
1075
|
-
throw error;
|
|
1076
|
-
} finally {
|
|
1077
|
-
session.endSession();
|
|
1078
|
-
}
|
|
1079
|
-
}
|
|
1080
|
-
/**
|
|
1081
|
-
* Execute custom query with event emission
|
|
1082
|
-
*/
|
|
1083
|
-
async _executeQuery(buildQuery) {
|
|
1084
|
-
const operation = buildQuery.name || "custom";
|
|
1085
|
-
const context = await this._buildContext(operation, {});
|
|
1086
|
-
try {
|
|
1087
|
-
const result = await buildQuery(this.Model);
|
|
1088
|
-
this.emit(`after:${operation}`, { context, result });
|
|
1089
|
-
return result;
|
|
1090
|
-
} catch (error) {
|
|
1091
|
-
this.emit(`error:${operation}`, { context, error });
|
|
1092
|
-
throw this._handleError(error);
|
|
1093
|
-
}
|
|
1094
|
-
}
|
|
1095
|
-
/**
|
|
1096
|
-
* Build operation context and run before hooks
|
|
1097
|
-
*/
|
|
1098
|
-
async _buildContext(operation, options) {
|
|
1099
|
-
const context = { operation, model: this.model, ...options };
|
|
1100
|
-
const event = `before:${operation}`;
|
|
1101
|
-
const hooks = this._hooks.get(event) || [];
|
|
1102
|
-
for (const hook of hooks) {
|
|
1103
|
-
await hook(context);
|
|
1104
|
-
}
|
|
1105
|
-
return context;
|
|
1106
|
-
}
|
|
1107
|
-
/**
|
|
1108
|
-
* Parse sort string or object
|
|
1109
|
-
*/
|
|
1110
|
-
_parseSort(sort) {
|
|
1111
|
-
if (!sort) return { createdAt: -1 };
|
|
1112
|
-
if (typeof sort === "object") return sort;
|
|
1113
|
-
const sortOrder = sort.startsWith("-") ? -1 : 1;
|
|
1114
|
-
const sortField = sort.startsWith("-") ? sort.substring(1) : sort;
|
|
1115
|
-
return { [sortField]: sortOrder };
|
|
1116
|
-
}
|
|
1117
|
-
/**
|
|
1118
|
-
* Parse populate specification
|
|
1119
|
-
*/
|
|
1120
|
-
_parsePopulate(populate) {
|
|
1121
|
-
if (!populate) return [];
|
|
1122
|
-
if (typeof populate === "string") return populate.split(",").map((p) => p.trim());
|
|
1123
|
-
if (Array.isArray(populate)) return populate.map((p) => typeof p === "string" ? p.trim() : p);
|
|
1124
|
-
return [populate];
|
|
1125
|
-
}
|
|
1126
|
-
/**
|
|
1127
|
-
* Handle errors with proper HTTP status codes
|
|
1128
|
-
*/
|
|
1129
|
-
_handleError(error) {
|
|
1130
|
-
if (error instanceof mongoose__default.default.Error.ValidationError) {
|
|
1131
|
-
const messages = Object.values(error.errors).map((err) => err.message);
|
|
1132
|
-
return createError(400, `Validation Error: ${messages.join(", ")}`);
|
|
1133
|
-
}
|
|
1134
|
-
if (error instanceof mongoose__default.default.Error.CastError) {
|
|
1135
|
-
return createError(400, `Invalid ${error.path}: ${error.value}`);
|
|
1136
|
-
}
|
|
1137
|
-
if (error.status && error.message) return error;
|
|
1138
|
-
return createError(500, error.message || "Internal Server Error");
|
|
1139
|
-
}
|
|
1140
|
-
};
|
|
1141
|
-
|
|
1142
|
-
// src/utils/field-selection.ts
|
|
1143
|
-
function getFieldsForUser(user, preset) {
|
|
1144
|
-
if (!preset) {
|
|
1145
|
-
throw new Error("Field preset is required");
|
|
1146
|
-
}
|
|
1147
|
-
const fields = [...preset.public || []];
|
|
1148
|
-
if (user) {
|
|
1149
|
-
fields.push(...preset.authenticated || []);
|
|
1150
|
-
const roles = Array.isArray(user.roles) ? user.roles : user.roles ? [user.roles] : [];
|
|
1151
|
-
if (roles.includes("admin") || roles.includes("superadmin")) {
|
|
1152
|
-
fields.push(...preset.admin || []);
|
|
1153
|
-
}
|
|
1154
|
-
}
|
|
1155
|
-
return [...new Set(fields)];
|
|
1156
|
-
}
|
|
1157
|
-
function getMongooseProjection(user, preset) {
|
|
1158
|
-
const fields = getFieldsForUser(user, preset);
|
|
1159
|
-
return fields.join(" ");
|
|
1160
|
-
}
|
|
1161
|
-
function filterObject(obj, allowedFields) {
|
|
1162
|
-
if (!obj || typeof obj !== "object" || Array.isArray(obj)) {
|
|
1163
|
-
return obj;
|
|
1164
|
-
}
|
|
1165
|
-
const filtered = {};
|
|
1166
|
-
for (const field of allowedFields) {
|
|
1167
|
-
if (field in obj) {
|
|
1168
|
-
filtered[field] = obj[field];
|
|
1169
|
-
}
|
|
1170
|
-
}
|
|
1171
|
-
return filtered;
|
|
1172
|
-
}
|
|
1173
|
-
function filterResponseData(data, preset, user = null) {
|
|
1174
|
-
const allowedFields = getFieldsForUser(user, preset);
|
|
1175
|
-
if (Array.isArray(data)) {
|
|
1176
|
-
return data.map((item) => filterObject(item, allowedFields));
|
|
1177
|
-
}
|
|
1178
|
-
return filterObject(data, allowedFields);
|
|
1179
|
-
}
|
|
1180
|
-
function createFieldPreset(config) {
|
|
1181
|
-
return {
|
|
1182
|
-
public: config.public || [],
|
|
1183
|
-
authenticated: config.authenticated || [],
|
|
1184
|
-
admin: config.admin || []
|
|
1185
|
-
};
|
|
1186
|
-
}
|
|
1187
|
-
|
|
1188
|
-
// src/plugins/field-filter.plugin.ts
|
|
1189
|
-
function fieldFilterPlugin(fieldPreset) {
|
|
1190
|
-
return {
|
|
1191
|
-
name: "fieldFilter",
|
|
1192
|
-
apply(repo) {
|
|
1193
|
-
const applyFieldFiltering = (context) => {
|
|
1194
|
-
if (!fieldPreset) return;
|
|
1195
|
-
const user = context.context?.user || context.user;
|
|
1196
|
-
const fields = getFieldsForUser(user, fieldPreset);
|
|
1197
|
-
const presetSelect = fields.join(" ");
|
|
1198
|
-
if (context.select) {
|
|
1199
|
-
context.select = `${presetSelect} ${context.select}`;
|
|
1200
|
-
} else {
|
|
1201
|
-
context.select = presetSelect;
|
|
1202
|
-
}
|
|
1203
|
-
};
|
|
1204
|
-
repo.on("before:getAll", applyFieldFiltering);
|
|
1205
|
-
repo.on("before:getById", applyFieldFiltering);
|
|
1206
|
-
repo.on("before:getByQuery", applyFieldFiltering);
|
|
1207
|
-
}
|
|
1208
|
-
};
|
|
1209
|
-
}
|
|
1210
|
-
|
|
1211
|
-
// src/plugins/timestamp.plugin.ts
|
|
1212
|
-
function timestampPlugin() {
|
|
1213
|
-
return {
|
|
1214
|
-
name: "timestamp",
|
|
1215
|
-
apply(repo) {
|
|
1216
|
-
repo.on("before:create", (context) => {
|
|
1217
|
-
if (!context.data) return;
|
|
1218
|
-
const now = /* @__PURE__ */ new Date();
|
|
1219
|
-
if (!context.data.createdAt) context.data.createdAt = now;
|
|
1220
|
-
if (!context.data.updatedAt) context.data.updatedAt = now;
|
|
1221
|
-
});
|
|
1222
|
-
repo.on("before:update", (context) => {
|
|
1223
|
-
if (!context.data) return;
|
|
1224
|
-
context.data.updatedAt = /* @__PURE__ */ new Date();
|
|
1225
|
-
});
|
|
1226
|
-
}
|
|
1227
|
-
};
|
|
1228
|
-
}
|
|
1229
|
-
|
|
1230
|
-
// src/plugins/audit-log.plugin.ts
|
|
1231
|
-
function auditLogPlugin(logger) {
|
|
1232
|
-
return {
|
|
1233
|
-
name: "auditLog",
|
|
1234
|
-
apply(repo) {
|
|
1235
|
-
repo.on("after:create", ({ context, result }) => {
|
|
1236
|
-
logger?.info?.("Document created", {
|
|
1237
|
-
model: context.model || repo.model,
|
|
1238
|
-
id: result?._id,
|
|
1239
|
-
userId: context.user?._id || context.user?.id,
|
|
1240
|
-
organizationId: context.organizationId
|
|
1241
|
-
});
|
|
1242
|
-
});
|
|
1243
|
-
repo.on("after:update", ({ context, result }) => {
|
|
1244
|
-
logger?.info?.("Document updated", {
|
|
1245
|
-
model: context.model || repo.model,
|
|
1246
|
-
id: context.id || result?._id,
|
|
1247
|
-
userId: context.user?._id || context.user?.id,
|
|
1248
|
-
organizationId: context.organizationId
|
|
1249
|
-
});
|
|
1250
|
-
});
|
|
1251
|
-
repo.on("after:delete", ({ context }) => {
|
|
1252
|
-
logger?.info?.("Document deleted", {
|
|
1253
|
-
model: context.model || repo.model,
|
|
1254
|
-
id: context.id,
|
|
1255
|
-
userId: context.user?._id || context.user?.id,
|
|
1256
|
-
organizationId: context.organizationId
|
|
1257
|
-
});
|
|
1258
|
-
});
|
|
1259
|
-
repo.on("error:create", ({ context, error }) => {
|
|
1260
|
-
logger?.error?.("Create failed", {
|
|
1261
|
-
model: context.model || repo.model,
|
|
1262
|
-
error: error.message,
|
|
1263
|
-
userId: context.user?._id || context.user?.id
|
|
1264
|
-
});
|
|
1265
|
-
});
|
|
1266
|
-
repo.on("error:update", ({ context, error }) => {
|
|
1267
|
-
logger?.error?.("Update failed", {
|
|
1268
|
-
model: context.model || repo.model,
|
|
1269
|
-
id: context.id,
|
|
1270
|
-
error: error.message,
|
|
1271
|
-
userId: context.user?._id || context.user?.id
|
|
1272
|
-
});
|
|
1273
|
-
});
|
|
1274
|
-
repo.on("error:delete", ({ context, error }) => {
|
|
1275
|
-
logger?.error?.("Delete failed", {
|
|
1276
|
-
model: context.model || repo.model,
|
|
1277
|
-
id: context.id,
|
|
1278
|
-
error: error.message,
|
|
1279
|
-
userId: context.user?._id || context.user?.id
|
|
1280
|
-
});
|
|
1281
|
-
});
|
|
1282
|
-
}
|
|
1283
|
-
};
|
|
1284
|
-
}
|
|
1285
|
-
|
|
1286
|
-
// src/plugins/soft-delete.plugin.ts
|
|
1287
|
-
function softDeletePlugin(options = {}) {
|
|
1288
|
-
const deletedField = options.deletedField || "deletedAt";
|
|
1289
|
-
const deletedByField = options.deletedByField || "deletedBy";
|
|
1290
|
-
return {
|
|
1291
|
-
name: "softDelete",
|
|
1292
|
-
apply(repo) {
|
|
1293
|
-
repo.on("before:delete", async (context) => {
|
|
1294
|
-
if (options.soft !== false) {
|
|
1295
|
-
const updateData = {
|
|
1296
|
-
[deletedField]: /* @__PURE__ */ new Date()
|
|
1297
|
-
};
|
|
1298
|
-
if (context.user) {
|
|
1299
|
-
updateData[deletedByField] = context.user._id || context.user.id;
|
|
1300
|
-
}
|
|
1301
|
-
await repo.Model.findByIdAndUpdate(context.id, updateData, { session: context.session });
|
|
1302
|
-
context.softDeleted = true;
|
|
1303
|
-
}
|
|
1304
|
-
});
|
|
1305
|
-
repo.on("before:getAll", (context) => {
|
|
1306
|
-
if (!context.includeDeleted && options.soft !== false) {
|
|
1307
|
-
const queryParams = context.queryParams || {};
|
|
1308
|
-
queryParams.filters = {
|
|
1309
|
-
...queryParams.filters || {},
|
|
1310
|
-
[deletedField]: { $exists: false }
|
|
1311
|
-
};
|
|
1312
|
-
context.queryParams = queryParams;
|
|
1313
|
-
}
|
|
1314
|
-
});
|
|
1315
|
-
repo.on("before:getById", (context) => {
|
|
1316
|
-
if (!context.includeDeleted && options.soft !== false) {
|
|
1317
|
-
context.query = {
|
|
1318
|
-
...context.query || {},
|
|
1319
|
-
[deletedField]: { $exists: false }
|
|
1320
|
-
};
|
|
1321
|
-
}
|
|
1322
|
-
});
|
|
1323
|
-
}
|
|
1324
|
-
};
|
|
1325
|
-
}
|
|
1326
|
-
|
|
1327
|
-
// src/plugins/method-registry.plugin.ts
|
|
1328
|
-
function methodRegistryPlugin() {
|
|
1329
|
-
return {
|
|
1330
|
-
name: "method-registry",
|
|
1331
|
-
apply(repo) {
|
|
1332
|
-
const registeredMethods = [];
|
|
1333
|
-
repo.registerMethod = function(name, fn) {
|
|
1334
|
-
if (repo[name]) {
|
|
1335
|
-
throw new Error(
|
|
1336
|
-
`Cannot register method '${name}': Method already exists on repository. Choose a different name or use a plugin that doesn't conflict.`
|
|
1337
|
-
);
|
|
1338
|
-
}
|
|
1339
|
-
if (!name || typeof name !== "string") {
|
|
1340
|
-
throw new Error("Method name must be a non-empty string");
|
|
1341
|
-
}
|
|
1342
|
-
if (typeof fn !== "function") {
|
|
1343
|
-
throw new Error(`Method '${name}' must be a function`);
|
|
1344
|
-
}
|
|
1345
|
-
repo[name] = fn.bind(repo);
|
|
1346
|
-
registeredMethods.push(name);
|
|
1347
|
-
repo.emit("method:registered", { name, fn });
|
|
1348
|
-
};
|
|
1349
|
-
repo.hasMethod = function(name) {
|
|
1350
|
-
return typeof repo[name] === "function";
|
|
1351
|
-
};
|
|
1352
|
-
repo.getRegisteredMethods = function() {
|
|
1353
|
-
return [...registeredMethods];
|
|
1354
|
-
};
|
|
1355
|
-
}
|
|
1356
|
-
};
|
|
1357
|
-
}
|
|
1358
|
-
|
|
1359
|
-
// src/plugins/validation-chain.plugin.ts
|
|
1360
|
-
function validationChainPlugin(validators = [], options = {}) {
|
|
1361
|
-
const { stopOnFirstError = true } = options;
|
|
1362
|
-
validators.forEach((v, idx) => {
|
|
1363
|
-
if (!v.name || typeof v.name !== "string") {
|
|
1364
|
-
throw new Error(`Validator at index ${idx} missing 'name' (string)`);
|
|
1365
|
-
}
|
|
1366
|
-
if (typeof v.validate !== "function") {
|
|
1367
|
-
throw new Error(`Validator '${v.name}' missing 'validate' function`);
|
|
1368
|
-
}
|
|
1369
|
-
});
|
|
1370
|
-
const validatorsByOperation = {
|
|
1371
|
-
create: [],
|
|
1372
|
-
update: [],
|
|
1373
|
-
delete: [],
|
|
1374
|
-
createMany: []
|
|
1375
|
-
};
|
|
1376
|
-
const allOperationsValidators = [];
|
|
1377
|
-
validators.forEach((v) => {
|
|
1378
|
-
if (!v.operations || v.operations.length === 0) {
|
|
1379
|
-
allOperationsValidators.push(v);
|
|
1380
|
-
} else {
|
|
1381
|
-
v.operations.forEach((op) => {
|
|
1382
|
-
if (validatorsByOperation[op]) {
|
|
1383
|
-
validatorsByOperation[op].push(v);
|
|
1384
|
-
}
|
|
1385
|
-
});
|
|
1386
|
-
}
|
|
1387
|
-
});
|
|
1388
|
-
return {
|
|
1389
|
-
name: "validation-chain",
|
|
1390
|
-
apply(repo) {
|
|
1391
|
-
const getValidatorsForOperation = (operation) => {
|
|
1392
|
-
const specific = validatorsByOperation[operation] || [];
|
|
1393
|
-
return [...allOperationsValidators, ...specific];
|
|
1394
|
-
};
|
|
1395
|
-
const runValidators = async (operation, context) => {
|
|
1396
|
-
const operationValidators = getValidatorsForOperation(operation);
|
|
1397
|
-
const errors = [];
|
|
1398
|
-
for (const validator of operationValidators) {
|
|
1399
|
-
try {
|
|
1400
|
-
await validator.validate(context, repo);
|
|
1401
|
-
} catch (error) {
|
|
1402
|
-
if (stopOnFirstError) {
|
|
1403
|
-
throw error;
|
|
1404
|
-
}
|
|
1405
|
-
errors.push({
|
|
1406
|
-
validator: validator.name,
|
|
1407
|
-
error: error.message || String(error)
|
|
1408
|
-
});
|
|
1409
|
-
}
|
|
1410
|
-
}
|
|
1411
|
-
if (errors.length > 0) {
|
|
1412
|
-
const err = createError(
|
|
1413
|
-
400,
|
|
1414
|
-
`Validation failed: ${errors.map((e) => `[${e.validator}] ${e.error}`).join("; ")}`
|
|
1415
|
-
);
|
|
1416
|
-
err.validationErrors = errors;
|
|
1417
|
-
throw err;
|
|
1418
|
-
}
|
|
1419
|
-
};
|
|
1420
|
-
repo.on("before:create", async (context) => runValidators("create", context));
|
|
1421
|
-
repo.on("before:createMany", async (context) => runValidators("createMany", context));
|
|
1422
|
-
repo.on("before:update", async (context) => runValidators("update", context));
|
|
1423
|
-
repo.on("before:delete", async (context) => runValidators("delete", context));
|
|
1424
|
-
}
|
|
1425
|
-
};
|
|
1426
|
-
}
|
|
1427
|
-
function blockIf(name, operations, condition, errorMessage) {
|
|
1428
|
-
return {
|
|
1429
|
-
name,
|
|
1430
|
-
operations,
|
|
1431
|
-
validate: (context) => {
|
|
1432
|
-
if (condition(context)) {
|
|
1433
|
-
throw createError(403, errorMessage);
|
|
1434
|
-
}
|
|
1435
|
-
}
|
|
1436
|
-
};
|
|
1437
|
-
}
|
|
1438
|
-
function requireField(field, operations = ["create"]) {
|
|
1439
|
-
return {
|
|
1440
|
-
name: `require-${field}`,
|
|
1441
|
-
operations,
|
|
1442
|
-
validate: (context) => {
|
|
1443
|
-
if (!context.data || context.data[field] === void 0 || context.data[field] === null) {
|
|
1444
|
-
throw createError(400, `Field '${field}' is required`);
|
|
1445
|
-
}
|
|
1446
|
-
}
|
|
1447
|
-
};
|
|
1448
|
-
}
|
|
1449
|
-
function autoInject(field, getter, operations = ["create"]) {
|
|
1450
|
-
return {
|
|
1451
|
-
name: `auto-inject-${field}`,
|
|
1452
|
-
operations,
|
|
1453
|
-
validate: (context) => {
|
|
1454
|
-
if (context.data && !(field in context.data)) {
|
|
1455
|
-
const value = getter(context);
|
|
1456
|
-
if (value !== null && value !== void 0) {
|
|
1457
|
-
context.data[field] = value;
|
|
1458
|
-
}
|
|
1459
|
-
}
|
|
1460
|
-
}
|
|
1461
|
-
};
|
|
1462
|
-
}
|
|
1463
|
-
function immutableField(field) {
|
|
1464
|
-
return {
|
|
1465
|
-
name: `immutable-${field}`,
|
|
1466
|
-
operations: ["update"],
|
|
1467
|
-
validate: (context) => {
|
|
1468
|
-
if (context.data && field in context.data) {
|
|
1469
|
-
throw createError(400, `Field '${field}' cannot be modified`);
|
|
1470
|
-
}
|
|
1471
|
-
}
|
|
1472
|
-
};
|
|
1473
|
-
}
|
|
1474
|
-
function uniqueField(field, errorMessage) {
|
|
1475
|
-
return {
|
|
1476
|
-
name: `unique-${field}`,
|
|
1477
|
-
operations: ["create", "update"],
|
|
1478
|
-
validate: async (context, repo) => {
|
|
1479
|
-
if (!context.data || !context.data[field] || !repo) return;
|
|
1480
|
-
const query = { [field]: context.data[field] };
|
|
1481
|
-
const getByQuery2 = repo.getByQuery;
|
|
1482
|
-
if (typeof getByQuery2 !== "function") return;
|
|
1483
|
-
const existing = await getByQuery2.call(repo, query, {
|
|
1484
|
-
select: "_id",
|
|
1485
|
-
lean: true,
|
|
1486
|
-
throwOnNotFound: false
|
|
1487
|
-
});
|
|
1488
|
-
if (existing && String(existing._id) !== String(context.id)) {
|
|
1489
|
-
throw createError(409, errorMessage || `${field} already exists`);
|
|
1490
|
-
}
|
|
1491
|
-
}
|
|
1492
|
-
};
|
|
1493
|
-
}
|
|
1494
|
-
|
|
1495
|
-
// src/plugins/mongo-operations.plugin.ts
|
|
1496
|
-
function mongoOperationsPlugin() {
|
|
1497
|
-
return {
|
|
1498
|
-
name: "mongo-operations",
|
|
1499
|
-
apply(repo) {
|
|
1500
|
-
if (!repo.registerMethod) {
|
|
1501
|
-
throw new Error(
|
|
1502
|
-
"mongoOperationsPlugin requires methodRegistryPlugin. Add methodRegistryPlugin() before mongoOperationsPlugin() in plugins array."
|
|
1503
|
-
);
|
|
1504
|
-
}
|
|
1505
|
-
repo.registerMethod("upsert", async function(query, data, options = {}) {
|
|
1506
|
-
return upsert(this.Model, query, data, options);
|
|
1507
|
-
});
|
|
1508
|
-
const validateAndUpdateNumeric = async function(id, field, value, operator, operationName, options) {
|
|
1509
|
-
if (typeof value !== "number") {
|
|
1510
|
-
throw createError(400, `${operationName} value must be a number`);
|
|
1511
|
-
}
|
|
1512
|
-
return this.update(id, { [operator]: { [field]: value } }, options);
|
|
1513
|
-
};
|
|
1514
|
-
repo.registerMethod("increment", async function(id, field, value = 1, options = {}) {
|
|
1515
|
-
return validateAndUpdateNumeric.call(this, id, field, value, "$inc", "Increment", options);
|
|
1516
|
-
});
|
|
1517
|
-
repo.registerMethod("decrement", async function(id, field, value = 1, options = {}) {
|
|
1518
|
-
return validateAndUpdateNumeric.call(this, id, field, -value, "$inc", "Decrement", options);
|
|
1519
|
-
});
|
|
1520
|
-
const applyOperator = function(id, field, value, operator, options) {
|
|
1521
|
-
return this.update(id, { [operator]: { [field]: value } }, options);
|
|
1522
|
-
};
|
|
1523
|
-
repo.registerMethod("pushToArray", async function(id, field, value, options = {}) {
|
|
1524
|
-
return applyOperator.call(this, id, field, value, "$push", options);
|
|
1525
|
-
});
|
|
1526
|
-
repo.registerMethod("pullFromArray", async function(id, field, value, options = {}) {
|
|
1527
|
-
return applyOperator.call(this, id, field, value, "$pull", options);
|
|
1528
|
-
});
|
|
1529
|
-
repo.registerMethod("addToSet", async function(id, field, value, options = {}) {
|
|
1530
|
-
return applyOperator.call(this, id, field, value, "$addToSet", options);
|
|
1531
|
-
});
|
|
1532
|
-
repo.registerMethod("setField", async function(id, field, value, options = {}) {
|
|
1533
|
-
return applyOperator.call(this, id, field, value, "$set", options);
|
|
1534
|
-
});
|
|
1535
|
-
repo.registerMethod("unsetField", async function(id, fields, options = {}) {
|
|
1536
|
-
const fieldArray = Array.isArray(fields) ? fields : [fields];
|
|
1537
|
-
const unsetObj = fieldArray.reduce((acc, field) => {
|
|
1538
|
-
acc[field] = "";
|
|
1539
|
-
return acc;
|
|
1540
|
-
}, {});
|
|
1541
|
-
return this.update(id, { $unset: unsetObj }, options);
|
|
1542
|
-
});
|
|
1543
|
-
repo.registerMethod("renameField", async function(id, oldName, newName, options = {}) {
|
|
1544
|
-
return this.update(id, { $rename: { [oldName]: newName } }, options);
|
|
1545
|
-
});
|
|
1546
|
-
repo.registerMethod("multiplyField", async function(id, field, multiplier, options = {}) {
|
|
1547
|
-
return validateAndUpdateNumeric.call(this, id, field, multiplier, "$mul", "Multiplier", options);
|
|
1548
|
-
});
|
|
1549
|
-
repo.registerMethod("setMin", async function(id, field, value, options = {}) {
|
|
1550
|
-
return applyOperator.call(this, id, field, value, "$min", options);
|
|
1551
|
-
});
|
|
1552
|
-
repo.registerMethod("setMax", async function(id, field, value, options = {}) {
|
|
1553
|
-
return applyOperator.call(this, id, field, value, "$max", options);
|
|
1554
|
-
});
|
|
1555
|
-
}
|
|
1556
|
-
};
|
|
1557
|
-
}
|
|
1558
|
-
|
|
1559
|
-
// src/plugins/batch-operations.plugin.ts
|
|
1560
|
-
function batchOperationsPlugin() {
|
|
1561
|
-
return {
|
|
1562
|
-
name: "batch-operations",
|
|
1563
|
-
apply(repo) {
|
|
1564
|
-
if (!repo.registerMethod) {
|
|
1565
|
-
throw new Error("batchOperationsPlugin requires methodRegistryPlugin");
|
|
1566
|
-
}
|
|
1567
|
-
repo.registerMethod("updateMany", async function(query, data, options = {}) {
|
|
1568
|
-
const _buildContext = this._buildContext;
|
|
1569
|
-
const context = await _buildContext.call(this, "updateMany", { query, data, options });
|
|
1570
|
-
try {
|
|
1571
|
-
this.emit("before:updateMany", context);
|
|
1572
|
-
const result = await this.Model.updateMany(query, data, {
|
|
1573
|
-
runValidators: true,
|
|
1574
|
-
session: options.session
|
|
1575
|
-
}).exec();
|
|
1576
|
-
this.emit("after:updateMany", { context, result });
|
|
1577
|
-
return result;
|
|
1578
|
-
} catch (error) {
|
|
1579
|
-
this.emit("error:updateMany", { context, error });
|
|
1580
|
-
const _handleError = this._handleError;
|
|
1581
|
-
throw _handleError.call(this, error);
|
|
1582
|
-
}
|
|
1583
|
-
});
|
|
1584
|
-
repo.registerMethod("deleteMany", async function(query, options = {}) {
|
|
1585
|
-
const _buildContext = this._buildContext;
|
|
1586
|
-
const context = await _buildContext.call(this, "deleteMany", { query, options });
|
|
1587
|
-
try {
|
|
1588
|
-
this.emit("before:deleteMany", context);
|
|
1589
|
-
const result = await this.Model.deleteMany(query, {
|
|
1590
|
-
session: options.session
|
|
1591
|
-
}).exec();
|
|
1592
|
-
this.emit("after:deleteMany", { context, result });
|
|
1593
|
-
return result;
|
|
1594
|
-
} catch (error) {
|
|
1595
|
-
this.emit("error:deleteMany", { context, error });
|
|
1596
|
-
const _handleError = this._handleError;
|
|
1597
|
-
throw _handleError.call(this, error);
|
|
1598
|
-
}
|
|
1599
|
-
});
|
|
1600
|
-
}
|
|
1601
|
-
};
|
|
1602
|
-
}
|
|
1603
|
-
|
|
1604
|
-
// src/plugins/aggregate-helpers.plugin.ts
|
|
1605
|
-
function aggregateHelpersPlugin() {
|
|
1606
|
-
return {
|
|
1607
|
-
name: "aggregate-helpers",
|
|
1608
|
-
apply(repo) {
|
|
1609
|
-
if (!repo.registerMethod) {
|
|
1610
|
-
throw new Error("aggregateHelpersPlugin requires methodRegistryPlugin");
|
|
1611
|
-
}
|
|
1612
|
-
repo.registerMethod("groupBy", async function(field, options = {}) {
|
|
1613
|
-
const pipeline = [
|
|
1614
|
-
{ $group: { _id: `$${field}`, count: { $sum: 1 } } },
|
|
1615
|
-
{ $sort: { count: -1 } }
|
|
1616
|
-
];
|
|
1617
|
-
if (options.limit) {
|
|
1618
|
-
pipeline.push({ $limit: options.limit });
|
|
1619
|
-
}
|
|
1620
|
-
const aggregate2 = this.aggregate;
|
|
1621
|
-
return aggregate2.call(this, pipeline, options);
|
|
1622
|
-
});
|
|
1623
|
-
const aggregateOperation = async function(field, operator, resultKey, query = {}, options = {}) {
|
|
1624
|
-
const pipeline = [
|
|
1625
|
-
{ $match: query },
|
|
1626
|
-
{ $group: { _id: null, [resultKey]: { [operator]: `$${field}` } } }
|
|
1627
|
-
];
|
|
1628
|
-
const aggregate2 = this.aggregate;
|
|
1629
|
-
const result = await aggregate2.call(this, pipeline, options);
|
|
1630
|
-
return result[0]?.[resultKey] || 0;
|
|
1631
|
-
};
|
|
1632
|
-
repo.registerMethod("sum", async function(field, query = {}, options = {}) {
|
|
1633
|
-
return aggregateOperation.call(this, field, "$sum", "total", query, options);
|
|
1634
|
-
});
|
|
1635
|
-
repo.registerMethod("average", async function(field, query = {}, options = {}) {
|
|
1636
|
-
return aggregateOperation.call(this, field, "$avg", "avg", query, options);
|
|
1637
|
-
});
|
|
1638
|
-
repo.registerMethod("min", async function(field, query = {}, options = {}) {
|
|
1639
|
-
return aggregateOperation.call(this, field, "$min", "min", query, options);
|
|
1640
|
-
});
|
|
1641
|
-
repo.registerMethod("max", async function(field, query = {}, options = {}) {
|
|
1642
|
-
return aggregateOperation.call(this, field, "$max", "max", query, options);
|
|
1643
|
-
});
|
|
1644
|
-
}
|
|
1645
|
-
};
|
|
1646
|
-
}
|
|
1647
|
-
|
|
1648
|
-
// src/plugins/subdocument.plugin.ts
|
|
1649
|
-
function subdocumentPlugin() {
|
|
1650
|
-
return {
|
|
1651
|
-
name: "subdocument",
|
|
1652
|
-
apply(repo) {
|
|
1653
|
-
if (!repo.registerMethod) {
|
|
1654
|
-
throw new Error("subdocumentPlugin requires methodRegistryPlugin");
|
|
1655
|
-
}
|
|
1656
|
-
repo.registerMethod("addSubdocument", async function(parentId, arrayPath, subData, options = {}) {
|
|
1657
|
-
const update2 = this.update;
|
|
1658
|
-
return update2.call(this, parentId, { $push: { [arrayPath]: subData } }, options);
|
|
1659
|
-
});
|
|
1660
|
-
repo.registerMethod("getSubdocument", async function(parentId, arrayPath, subId, options = {}) {
|
|
1661
|
-
const _executeQuery = this._executeQuery;
|
|
1662
|
-
return _executeQuery.call(this, async (Model) => {
|
|
1663
|
-
const parent = await Model.findById(parentId).session(options.session).exec();
|
|
1664
|
-
if (!parent) throw createError(404, "Parent not found");
|
|
1665
|
-
const parentObj = parent;
|
|
1666
|
-
const arrayField = parentObj[arrayPath];
|
|
1667
|
-
if (!arrayField || typeof arrayField.id !== "function") {
|
|
1668
|
-
throw createError(404, "Array field not found");
|
|
1669
|
-
}
|
|
1670
|
-
const sub = arrayField.id(subId);
|
|
1671
|
-
if (!sub) throw createError(404, "Subdocument not found");
|
|
1672
|
-
return options.lean && typeof sub.toObject === "function" ? sub.toObject() : sub;
|
|
1673
|
-
});
|
|
1674
|
-
});
|
|
1675
|
-
repo.registerMethod("updateSubdocument", async function(parentId, arrayPath, subId, updateData, options = {}) {
|
|
1676
|
-
const _executeQuery = this._executeQuery;
|
|
1677
|
-
return _executeQuery.call(this, async (Model) => {
|
|
1678
|
-
const query = { _id: parentId, [`${arrayPath}._id`]: subId };
|
|
1679
|
-
const update2 = { $set: { [`${arrayPath}.$`]: { ...updateData, _id: subId } } };
|
|
1680
|
-
const result = await Model.findOneAndUpdate(query, update2, {
|
|
1681
|
-
new: true,
|
|
1682
|
-
runValidators: true,
|
|
1683
|
-
session: options.session
|
|
1684
|
-
}).exec();
|
|
1685
|
-
if (!result) throw createError(404, "Parent or subdocument not found");
|
|
1686
|
-
return result;
|
|
1687
|
-
});
|
|
1688
|
-
});
|
|
1689
|
-
repo.registerMethod("deleteSubdocument", async function(parentId, arrayPath, subId, options = {}) {
|
|
1690
|
-
const update2 = this.update;
|
|
1691
|
-
return update2.call(this, parentId, { $pull: { [arrayPath]: { _id: subId } } }, options);
|
|
1692
|
-
});
|
|
1693
|
-
}
|
|
1694
|
-
};
|
|
1695
|
-
}
|
|
1696
|
-
|
|
1697
|
-
// src/utils/cache-keys.ts
|
|
1698
|
-
function hashString(str) {
|
|
1699
|
-
let hash = 5381;
|
|
1700
|
-
for (let i = 0; i < str.length; i++) {
|
|
1701
|
-
hash = (hash << 5) + hash ^ str.charCodeAt(i);
|
|
1702
|
-
}
|
|
1703
|
-
return (hash >>> 0).toString(16);
|
|
1704
|
-
}
|
|
1705
|
-
function stableStringify(obj) {
|
|
1706
|
-
if (obj === null || obj === void 0) return "";
|
|
1707
|
-
if (typeof obj !== "object") return String(obj);
|
|
1708
|
-
if (Array.isArray(obj)) {
|
|
1709
|
-
return "[" + obj.map(stableStringify).join(",") + "]";
|
|
1710
|
-
}
|
|
1711
|
-
const sorted = Object.keys(obj).sort().map((key) => `${key}:${stableStringify(obj[key])}`);
|
|
1712
|
-
return "{" + sorted.join(",") + "}";
|
|
1713
|
-
}
|
|
1714
|
-
function byIdKey(prefix, model, id) {
|
|
1715
|
-
return `${prefix}:id:${model}:${id}`;
|
|
1716
|
-
}
|
|
1717
|
-
function byQueryKey(prefix, model, query, options) {
|
|
1718
|
-
const hashInput = stableStringify({ q: query, s: options?.select, p: options?.populate });
|
|
1719
|
-
return `${prefix}:one:${model}:${hashString(hashInput)}`;
|
|
1720
|
-
}
|
|
1721
|
-
function listQueryKey(prefix, model, version, params) {
|
|
1722
|
-
const hashInput = stableStringify({
|
|
1723
|
-
f: params.filters,
|
|
1724
|
-
s: params.sort,
|
|
1725
|
-
pg: params.page,
|
|
1726
|
-
lm: params.limit,
|
|
1727
|
-
af: params.after,
|
|
1728
|
-
sl: params.select,
|
|
1729
|
-
pp: params.populate
|
|
1730
|
-
});
|
|
1731
|
-
return `${prefix}:list:${model}:${version}:${hashString(hashInput)}`;
|
|
1732
|
-
}
|
|
1733
|
-
function versionKey(prefix, model) {
|
|
1734
|
-
return `${prefix}:ver:${model}`;
|
|
1735
|
-
}
|
|
1736
|
-
function modelPattern(prefix, model) {
|
|
1737
|
-
return `${prefix}:*:${model}:*`;
|
|
1738
|
-
}
|
|
1739
|
-
|
|
1740
|
-
// src/plugins/cache.plugin.ts
|
|
1741
|
-
function cachePlugin(options) {
|
|
1742
|
-
const config = {
|
|
1743
|
-
adapter: options.adapter,
|
|
1744
|
-
ttl: options.ttl ?? 60,
|
|
1745
|
-
byIdTtl: options.byIdTtl ?? options.ttl ?? 60,
|
|
1746
|
-
queryTtl: options.queryTtl ?? options.ttl ?? 60,
|
|
1747
|
-
prefix: options.prefix ?? "mk",
|
|
1748
|
-
debug: options.debug ?? false,
|
|
1749
|
-
skipIfLargeLimit: options.skipIf?.largeLimit ?? 100
|
|
1750
|
-
};
|
|
1751
|
-
const stats = {
|
|
1752
|
-
hits: 0,
|
|
1753
|
-
misses: 0,
|
|
1754
|
-
sets: 0,
|
|
1755
|
-
invalidations: 0
|
|
1756
|
-
};
|
|
1757
|
-
let collectionVersion = 0;
|
|
1758
|
-
const log = (msg, data) => {
|
|
1759
|
-
if (config.debug) {
|
|
1760
|
-
console.log(`[mongokit:cache] ${msg}`, data ?? "");
|
|
1761
|
-
}
|
|
1762
|
-
};
|
|
1763
|
-
return {
|
|
1764
|
-
name: "cache",
|
|
1765
|
-
apply(repo) {
|
|
1766
|
-
const model = repo.model;
|
|
1767
|
-
(async () => {
|
|
1768
|
-
try {
|
|
1769
|
-
const cached = await config.adapter.get(versionKey(config.prefix, model));
|
|
1770
|
-
if (cached !== null) {
|
|
1771
|
-
collectionVersion = cached;
|
|
1772
|
-
log(`Initialized version for ${model}:`, collectionVersion);
|
|
1773
|
-
}
|
|
1774
|
-
} catch (e) {
|
|
1775
|
-
log(`Failed to initialize version for ${model}:`, e);
|
|
1776
|
-
}
|
|
1777
|
-
})();
|
|
1778
|
-
async function bumpVersion() {
|
|
1779
|
-
collectionVersion++;
|
|
1780
|
-
try {
|
|
1781
|
-
await config.adapter.set(versionKey(config.prefix, model), collectionVersion, config.ttl * 10);
|
|
1782
|
-
stats.invalidations++;
|
|
1783
|
-
log(`Bumped version for ${model} to:`, collectionVersion);
|
|
1784
|
-
} catch (e) {
|
|
1785
|
-
log(`Failed to bump version for ${model}:`, e);
|
|
1786
|
-
}
|
|
1787
|
-
}
|
|
1788
|
-
async function invalidateById(id) {
|
|
1789
|
-
const key = byIdKey(config.prefix, model, id);
|
|
1790
|
-
try {
|
|
1791
|
-
await config.adapter.del(key);
|
|
1792
|
-
stats.invalidations++;
|
|
1793
|
-
log(`Invalidated byId cache:`, key);
|
|
1794
|
-
} catch (e) {
|
|
1795
|
-
log(`Failed to invalidate byId cache:`, e);
|
|
1796
|
-
}
|
|
1797
|
-
}
|
|
1798
|
-
repo.on("before:getById", async (context) => {
|
|
1799
|
-
if (context.skipCache) {
|
|
1800
|
-
log(`Skipping cache for getById: ${context.id}`);
|
|
1801
|
-
return;
|
|
1802
|
-
}
|
|
1803
|
-
const id = String(context.id);
|
|
1804
|
-
const key = byIdKey(config.prefix, model, id);
|
|
1805
|
-
try {
|
|
1806
|
-
const cached = await config.adapter.get(key);
|
|
1807
|
-
if (cached !== null) {
|
|
1808
|
-
stats.hits++;
|
|
1809
|
-
log(`Cache HIT for getById:`, key);
|
|
1810
|
-
context._cacheHit = true;
|
|
1811
|
-
context._cachedResult = cached;
|
|
1812
|
-
} else {
|
|
1813
|
-
stats.misses++;
|
|
1814
|
-
log(`Cache MISS for getById:`, key);
|
|
1815
|
-
}
|
|
1816
|
-
} catch (e) {
|
|
1817
|
-
log(`Cache error for getById:`, e);
|
|
1818
|
-
stats.misses++;
|
|
1819
|
-
}
|
|
1820
|
-
});
|
|
1821
|
-
repo.on("before:getByQuery", async (context) => {
|
|
1822
|
-
if (context.skipCache) {
|
|
1823
|
-
log(`Skipping cache for getByQuery`);
|
|
1824
|
-
return;
|
|
1825
|
-
}
|
|
1826
|
-
const query = context.query || {};
|
|
1827
|
-
const key = byQueryKey(config.prefix, model, query, {
|
|
1828
|
-
select: context.select,
|
|
1829
|
-
populate: context.populate
|
|
1830
|
-
});
|
|
1831
|
-
try {
|
|
1832
|
-
const cached = await config.adapter.get(key);
|
|
1833
|
-
if (cached !== null) {
|
|
1834
|
-
stats.hits++;
|
|
1835
|
-
log(`Cache HIT for getByQuery:`, key);
|
|
1836
|
-
context._cacheHit = true;
|
|
1837
|
-
context._cachedResult = cached;
|
|
1838
|
-
} else {
|
|
1839
|
-
stats.misses++;
|
|
1840
|
-
log(`Cache MISS for getByQuery:`, key);
|
|
1841
|
-
}
|
|
1842
|
-
} catch (e) {
|
|
1843
|
-
log(`Cache error for getByQuery:`, e);
|
|
1844
|
-
stats.misses++;
|
|
1845
|
-
}
|
|
1846
|
-
});
|
|
1847
|
-
repo.on("before:getAll", async (context) => {
|
|
1848
|
-
if (context.skipCache) {
|
|
1849
|
-
log(`Skipping cache for getAll`);
|
|
1850
|
-
return;
|
|
1851
|
-
}
|
|
1852
|
-
const limit = context.limit;
|
|
1853
|
-
if (limit && limit > config.skipIfLargeLimit) {
|
|
1854
|
-
log(`Skipping cache for large query (limit: ${limit})`);
|
|
1855
|
-
return;
|
|
1856
|
-
}
|
|
1857
|
-
const params = {
|
|
1858
|
-
filters: context.filters,
|
|
1859
|
-
sort: context.sort,
|
|
1860
|
-
page: context.page,
|
|
1861
|
-
limit,
|
|
1862
|
-
after: context.after,
|
|
1863
|
-
select: context.select,
|
|
1864
|
-
populate: context.populate
|
|
1865
|
-
};
|
|
1866
|
-
const key = listQueryKey(config.prefix, model, collectionVersion, params);
|
|
1867
|
-
try {
|
|
1868
|
-
const cached = await config.adapter.get(key);
|
|
1869
|
-
if (cached !== null) {
|
|
1870
|
-
stats.hits++;
|
|
1871
|
-
log(`Cache HIT for getAll:`, key);
|
|
1872
|
-
context._cacheHit = true;
|
|
1873
|
-
context._cachedResult = cached;
|
|
1874
|
-
} else {
|
|
1875
|
-
stats.misses++;
|
|
1876
|
-
log(`Cache MISS for getAll:`, key);
|
|
1877
|
-
}
|
|
1878
|
-
} catch (e) {
|
|
1879
|
-
log(`Cache error for getAll:`, e);
|
|
1880
|
-
stats.misses++;
|
|
1881
|
-
}
|
|
1882
|
-
});
|
|
1883
|
-
repo.on("after:getById", async (payload) => {
|
|
1884
|
-
const { context, result } = payload;
|
|
1885
|
-
if (context._cacheHit) return;
|
|
1886
|
-
if (context.skipCache) return;
|
|
1887
|
-
if (result === null) return;
|
|
1888
|
-
const id = String(context.id);
|
|
1889
|
-
const key = byIdKey(config.prefix, model, id);
|
|
1890
|
-
const ttl = context.cacheTtl ?? config.byIdTtl;
|
|
1891
|
-
try {
|
|
1892
|
-
await config.adapter.set(key, result, ttl);
|
|
1893
|
-
stats.sets++;
|
|
1894
|
-
log(`Cached getById result:`, key);
|
|
1895
|
-
} catch (e) {
|
|
1896
|
-
log(`Failed to cache getById:`, e);
|
|
1897
|
-
}
|
|
1898
|
-
});
|
|
1899
|
-
repo.on("after:getByQuery", async (payload) => {
|
|
1900
|
-
const { context, result } = payload;
|
|
1901
|
-
if (context._cacheHit) return;
|
|
1902
|
-
if (context.skipCache) return;
|
|
1903
|
-
if (result === null) return;
|
|
1904
|
-
const query = context.query || {};
|
|
1905
|
-
const key = byQueryKey(config.prefix, model, query, {
|
|
1906
|
-
select: context.select,
|
|
1907
|
-
populate: context.populate
|
|
1908
|
-
});
|
|
1909
|
-
const ttl = context.cacheTtl ?? config.queryTtl;
|
|
1910
|
-
try {
|
|
1911
|
-
await config.adapter.set(key, result, ttl);
|
|
1912
|
-
stats.sets++;
|
|
1913
|
-
log(`Cached getByQuery result:`, key);
|
|
1914
|
-
} catch (e) {
|
|
1915
|
-
log(`Failed to cache getByQuery:`, e);
|
|
1916
|
-
}
|
|
1917
|
-
});
|
|
1918
|
-
repo.on("after:getAll", async (payload) => {
|
|
1919
|
-
const { context, result } = payload;
|
|
1920
|
-
if (context._cacheHit) return;
|
|
1921
|
-
if (context.skipCache) return;
|
|
1922
|
-
const limit = context.limit;
|
|
1923
|
-
if (limit && limit > config.skipIfLargeLimit) return;
|
|
1924
|
-
const params = {
|
|
1925
|
-
filters: context.filters,
|
|
1926
|
-
sort: context.sort,
|
|
1927
|
-
page: context.page,
|
|
1928
|
-
limit,
|
|
1929
|
-
after: context.after,
|
|
1930
|
-
select: context.select,
|
|
1931
|
-
populate: context.populate
|
|
1932
|
-
};
|
|
1933
|
-
const key = listQueryKey(config.prefix, model, collectionVersion, params);
|
|
1934
|
-
const ttl = context.cacheTtl ?? config.queryTtl;
|
|
1935
|
-
try {
|
|
1936
|
-
await config.adapter.set(key, result, ttl);
|
|
1937
|
-
stats.sets++;
|
|
1938
|
-
log(`Cached getAll result:`, key);
|
|
1939
|
-
} catch (e) {
|
|
1940
|
-
log(`Failed to cache getAll:`, e);
|
|
1941
|
-
}
|
|
1942
|
-
});
|
|
1943
|
-
repo.on("after:create", async () => {
|
|
1944
|
-
await bumpVersion();
|
|
1945
|
-
});
|
|
1946
|
-
repo.on("after:createMany", async () => {
|
|
1947
|
-
await bumpVersion();
|
|
1948
|
-
});
|
|
1949
|
-
repo.on("after:update", async (payload) => {
|
|
1950
|
-
const { context } = payload;
|
|
1951
|
-
const id = String(context.id);
|
|
1952
|
-
await Promise.all([
|
|
1953
|
-
invalidateById(id),
|
|
1954
|
-
bumpVersion()
|
|
1955
|
-
]);
|
|
1956
|
-
});
|
|
1957
|
-
repo.on("after:updateMany", async () => {
|
|
1958
|
-
await bumpVersion();
|
|
1959
|
-
});
|
|
1960
|
-
repo.on("after:delete", async (payload) => {
|
|
1961
|
-
const { context } = payload;
|
|
1962
|
-
const id = String(context.id);
|
|
1963
|
-
await Promise.all([
|
|
1964
|
-
invalidateById(id),
|
|
1965
|
-
bumpVersion()
|
|
1966
|
-
]);
|
|
1967
|
-
});
|
|
1968
|
-
repo.on("after:deleteMany", async () => {
|
|
1969
|
-
await bumpVersion();
|
|
1970
|
-
});
|
|
1971
|
-
repo.invalidateCache = async (id) => {
|
|
1972
|
-
await invalidateById(id);
|
|
1973
|
-
log(`Manual invalidation for ID:`, id);
|
|
1974
|
-
};
|
|
1975
|
-
repo.invalidateListCache = async () => {
|
|
1976
|
-
await bumpVersion();
|
|
1977
|
-
log(`Manual list cache invalidation for ${model}`);
|
|
1978
|
-
};
|
|
1979
|
-
repo.invalidateAllCache = async () => {
|
|
1980
|
-
if (config.adapter.clear) {
|
|
1981
|
-
try {
|
|
1982
|
-
await config.adapter.clear(modelPattern(config.prefix, model));
|
|
1983
|
-
stats.invalidations++;
|
|
1984
|
-
log(`Full cache invalidation for ${model}`);
|
|
1985
|
-
} catch (e) {
|
|
1986
|
-
log(`Failed full cache invalidation for ${model}:`, e);
|
|
1987
|
-
}
|
|
1988
|
-
} else {
|
|
1989
|
-
await bumpVersion();
|
|
1990
|
-
log(`Partial cache invalidation for ${model} (adapter.clear not available)`);
|
|
1991
|
-
}
|
|
1992
|
-
};
|
|
1993
|
-
repo.getCacheStats = () => ({ ...stats });
|
|
1994
|
-
repo.resetCacheStats = () => {
|
|
1995
|
-
stats.hits = 0;
|
|
1996
|
-
stats.misses = 0;
|
|
1997
|
-
stats.sets = 0;
|
|
1998
|
-
stats.invalidations = 0;
|
|
1999
|
-
};
|
|
2000
|
-
}
|
|
2001
|
-
};
|
|
2002
|
-
}
|
|
2003
|
-
|
|
2004
|
-
// src/utils/memory-cache.ts
|
|
2005
|
-
function createMemoryCache(maxEntries = 1e3) {
|
|
2006
|
-
const cache = /* @__PURE__ */ new Map();
|
|
2007
|
-
function cleanup() {
|
|
2008
|
-
const now = Date.now();
|
|
2009
|
-
for (const [key, entry] of cache) {
|
|
2010
|
-
if (entry.expiresAt < now) {
|
|
2011
|
-
cache.delete(key);
|
|
2012
|
-
}
|
|
2013
|
-
}
|
|
2014
|
-
}
|
|
2015
|
-
function evictOldest() {
|
|
2016
|
-
if (cache.size >= maxEntries) {
|
|
2017
|
-
const firstKey = cache.keys().next().value;
|
|
2018
|
-
if (firstKey) cache.delete(firstKey);
|
|
2019
|
-
}
|
|
2020
|
-
}
|
|
2021
|
-
return {
|
|
2022
|
-
async get(key) {
|
|
2023
|
-
cleanup();
|
|
2024
|
-
const entry = cache.get(key);
|
|
2025
|
-
if (!entry) return null;
|
|
2026
|
-
if (entry.expiresAt < Date.now()) {
|
|
2027
|
-
cache.delete(key);
|
|
2028
|
-
return null;
|
|
2029
|
-
}
|
|
2030
|
-
return entry.value;
|
|
2031
|
-
},
|
|
2032
|
-
async set(key, value, ttl) {
|
|
2033
|
-
cleanup();
|
|
2034
|
-
evictOldest();
|
|
2035
|
-
cache.set(key, {
|
|
2036
|
-
value,
|
|
2037
|
-
expiresAt: Date.now() + ttl * 1e3
|
|
2038
|
-
});
|
|
2039
|
-
},
|
|
2040
|
-
async del(key) {
|
|
2041
|
-
cache.delete(key);
|
|
2042
|
-
},
|
|
2043
|
-
async clear(pattern) {
|
|
2044
|
-
if (!pattern) {
|
|
2045
|
-
cache.clear();
|
|
2046
|
-
return;
|
|
2047
|
-
}
|
|
2048
|
-
const regex = new RegExp(
|
|
2049
|
-
"^" + pattern.replace(/\*/g, ".*").replace(/\?/g, ".") + "$"
|
|
2050
|
-
);
|
|
2051
|
-
for (const key of cache.keys()) {
|
|
2052
|
-
if (regex.test(key)) {
|
|
2053
|
-
cache.delete(key);
|
|
2054
|
-
}
|
|
2055
|
-
}
|
|
2056
|
-
}
|
|
2057
|
-
};
|
|
2058
|
-
}
|
|
2059
|
-
|
|
2060
|
-
// src/actions/index.ts
|
|
2061
|
-
var actions_exports = {};
|
|
2062
|
-
__export(actions_exports, {
|
|
2063
|
-
aggregate: () => aggregate_exports,
|
|
2064
|
-
create: () => create_exports,
|
|
2065
|
-
deleteActions: () => delete_exports,
|
|
2066
|
-
read: () => read_exports,
|
|
2067
|
-
update: () => update_exports
|
|
2068
|
-
});
|
|
2069
|
-
|
|
2070
|
-
// src/index.ts
|
|
2071
|
-
function createRepository(Model, plugins = []) {
|
|
2072
|
-
return new Repository(Model, plugins);
|
|
2073
|
-
}
|
|
2074
|
-
var index_default = Repository;
|
|
2075
|
-
/**
|
|
2076
|
-
* MongoKit - Event-driven repository pattern for MongoDB
|
|
2077
|
-
*
|
|
2078
|
-
* Production-grade MongoDB repositories with zero dependencies -
|
|
2079
|
-
* smart pagination, events, and plugins.
|
|
2080
|
-
*
|
|
2081
|
-
* @module @classytic/mongokit
|
|
2082
|
-
* @author Sadman Chowdhury (Github: @siam923)
|
|
2083
|
-
* @license MIT
|
|
2084
|
-
*
|
|
2085
|
-
* @example
|
|
2086
|
-
* ```typescript
|
|
2087
|
-
* import { Repository, createRepository } from '@classytic/mongokit';
|
|
2088
|
-
* import { timestampPlugin, softDeletePlugin } from '@classytic/mongokit';
|
|
2089
|
-
*
|
|
2090
|
-
* // Create repository with plugins
|
|
2091
|
-
* const userRepo = createRepository(UserModel, [
|
|
2092
|
-
* timestampPlugin(),
|
|
2093
|
-
* softDeletePlugin(),
|
|
2094
|
-
* ]);
|
|
2095
|
-
*
|
|
2096
|
-
* // Create
|
|
2097
|
-
* const user = await userRepo.create({ name: 'John', email: 'john@example.com' });
|
|
2098
|
-
*
|
|
2099
|
-
* // Read with pagination (auto-detects offset vs keyset)
|
|
2100
|
-
* const users = await userRepo.getAll({ page: 1, limit: 20 });
|
|
2101
|
-
*
|
|
2102
|
-
* // Keyset pagination for infinite scroll
|
|
2103
|
-
* const stream = await userRepo.getAll({ sort: { createdAt: -1 }, limit: 50 });
|
|
2104
|
-
* const nextStream = await userRepo.getAll({ after: stream.next, sort: { createdAt: -1 } });
|
|
2105
|
-
*
|
|
2106
|
-
* // Update
|
|
2107
|
-
* await userRepo.update(user._id, { name: 'John Doe' });
|
|
2108
|
-
*
|
|
2109
|
-
* // Delete
|
|
2110
|
-
* await userRepo.delete(user._id);
|
|
2111
|
-
* ```
|
|
2112
|
-
*/
|
|
2113
|
-
|
|
2114
|
-
exports.PaginationEngine = PaginationEngine;
|
|
2115
|
-
exports.Repository = Repository;
|
|
2116
|
-
exports.actions = actions_exports;
|
|
2117
|
-
exports.aggregateHelpersPlugin = aggregateHelpersPlugin;
|
|
2118
|
-
exports.auditLogPlugin = auditLogPlugin;
|
|
2119
|
-
exports.autoInject = autoInject;
|
|
2120
|
-
exports.batchOperationsPlugin = batchOperationsPlugin;
|
|
2121
|
-
exports.blockIf = blockIf;
|
|
2122
|
-
exports.cachePlugin = cachePlugin;
|
|
2123
|
-
exports.createError = createError;
|
|
2124
|
-
exports.createFieldPreset = createFieldPreset;
|
|
2125
|
-
exports.createMemoryCache = createMemoryCache;
|
|
2126
|
-
exports.createRepository = createRepository;
|
|
2127
|
-
exports.default = index_default;
|
|
2128
|
-
exports.fieldFilterPlugin = fieldFilterPlugin;
|
|
2129
|
-
exports.filterResponseData = filterResponseData;
|
|
2130
|
-
exports.getFieldsForUser = getFieldsForUser;
|
|
2131
|
-
exports.getMongooseProjection = getMongooseProjection;
|
|
2132
|
-
exports.immutableField = immutableField;
|
|
2133
|
-
exports.methodRegistryPlugin = methodRegistryPlugin;
|
|
2134
|
-
exports.mongoOperationsPlugin = mongoOperationsPlugin;
|
|
2135
|
-
exports.requireField = requireField;
|
|
2136
|
-
exports.softDeletePlugin = softDeletePlugin;
|
|
2137
|
-
exports.subdocumentPlugin = subdocumentPlugin;
|
|
2138
|
-
exports.timestampPlugin = timestampPlugin;
|
|
2139
|
-
exports.uniqueField = uniqueField;
|
|
2140
|
-
exports.validationChainPlugin = validationChainPlugin;
|
|
2141
|
-
//# sourceMappingURL=index.cjs.map
|
|
2142
|
-
//# sourceMappingURL=index.cjs.map
|