-
Notifications
You must be signed in to change notification settings - Fork 67
Expand file tree
/
Copy pathdata.controller.js
More file actions
727 lines (592 loc) · 21.1 KB
/
Copy pathdata.controller.js
File metadata and controls
727 lines (592 loc) · 21.1 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
const { sanitize } = require("@urbackend/common");
const mongoose = require("mongoose");
const { Project } = require("@urbackend/common");
const { getConnection } = require("@urbackend/common");
const { getCompiledModel } = require("@urbackend/common");
const { QueryEngine } = require("@urbackend/common");
const { validateData, validateUpdateData, aggregateSchema, webhookQueue } = require("@urbackend/common");
const { performance } = require('perf_hooks');
const { z } = require("zod");
const {
AppError,
ApiResponse,
enqueueCollectionCleanup,
syncCollectionCleanup
} = require("@urbackend/common");
const isDebug = process.env.DEBUG === 'true';
const isValidId = (id) => mongoose.Types.ObjectId.isValid(id);
const isDuplicateKeyError = (err) => {
return err && err.code === 11000;
};
const BLOCKED_AGGREGATION_STAGES = new Set(["$out", "$merge"]);
const containsBlockedAggregationStage = (pipeline = []) => {
return pipeline.some((stage) =>
Object.keys(stage || {}).some((key) => BLOCKED_AGGREGATION_STAGES.has(key)),
);
};
// INSERT DATA
module.exports.insertData = async (req, res, next) => {
try {
let start;
if (isDebug) start = performance.now();
const { collectionName } = req.params;
const project = req.project;
const collectionConfig = project.collections.find(
(c) => c.name === collectionName,
);
if (!collectionConfig)
return next(new AppError(404, "Collection not found"));
const schemaRules = collectionConfig.model;
const incomingData = req.body;
const { error, cleanData } = validateData(incomingData, schemaRules);
if (error) return next(new AppError(400, error));
// Prevent manual injection of soft-delete fields
delete cleanData.isDeleted;
delete cleanData.deletedAt;
const safeData = sanitize(cleanData);
let docSize = 0;
if (!project.resources.db.isExternal) {
const docForSize = safeData._id
? safeData
: { ...safeData, _id: new mongoose.Types.ObjectId() };
docSize = mongoose.mongo.BSON.calculateObjectSize(docForSize);
if ((project.databaseUsed || 0) + docSize > project.databaseLimit) {
return next(new AppError(403, "Database limit exceeded."));
}
}
const connection = await getConnection(project._id);
const Model = getCompiledModel(
connection,
collectionConfig,
project._id,
project.resources.db.isExternal,
);
const result = await Model.create(safeData);
if (!project.resources.db.isExternal) {
await Project.updateOne(
{ _id: project._id },
{ $inc: { databaseUsed: docSize } },
);
}
await webhookQueue.add('trigger-webhook', {
projectId: project._id,
event: 'document.inserted',
collection: collectionName,
payload: result.toObject ? result.toObject() : result
}, { removeOnComplete: true });
if (isDebug) console.log(`[DEBUG] insert data took ${(performance.now() - start).toFixed(2)}ms`);
return new ApiResponse(result).send(res, 201);
} catch (err) {
if (process.env.NODE_ENV !== 'test') {
console.error(err);
}
if (isDuplicateKeyError(err)) {
return next(new AppError(409, "Duplicate value violates unique constraint."));
}
return next(new AppError(500, "An error occurred while processing your request"));
}
};
// BULK INSERT DATA
module.exports.bulkInsertData = async (req, res, next) => {
try {
const MAX_BULK_INSERT_LIMIT = 100;
const { collectionName } = req.params;
const project = req.project;
const incomingData = req.body;
if (!Array.isArray(incomingData)) {
return next(new AppError(400, "Request body must be an array of objects"));
}
if (incomingData.length === 0) {
return next(new AppError(400, "Request body cannot be empty"));
}
if (incomingData.length > MAX_BULK_INSERT_LIMIT) {
return next(
new AppError(400, `Maximum ${MAX_BULK_INSERT_LIMIT} records allowed`)
);
}
const collectionConfig = project.collections.find(
(c) => c.name === collectionName
);
if (!collectionConfig) {
return next(new AppError(404, "Collection not found"));
}
const schemaRules = collectionConfig.model;
const validData = [];
const invalidIndices = [];
incomingData.forEach((item, index) => {
if (!item || typeof item !== "object" || Array.isArray(item)) {
invalidIndices.push(index);
return;
}
const { error, cleanData } = validateData(item, schemaRules);
if (error) {
invalidIndices.push(index);
} else {
// Prevent manual injection of soft-delete fields
delete cleanData.isDeleted;
delete cleanData.deletedAt;
validData.push(sanitize({
...cleanData,
isDeleted: false,
deletedAt: null
}));
}
});
if (invalidIndices.length > 0) {
return next(
new AppError(400, `Invalid records at index: ${invalidIndices.join(", ")}`)
);
}
const connection = await getConnection(project._id);
const Model = getCompiledModel(
connection,
collectionConfig,
project._id,
project.resources.db.isExternal
);
let totalDocSize = 0;
if (!project.resources.db.isExternal) {
for (const data of validData) {
const docForSize = data._id
? data
: { ...data, _id: new mongoose.Types.ObjectId() };
totalDocSize += mongoose.mongo.BSON.calculateObjectSize(docForSize);
}
if ((project.databaseUsed || 0) + totalDocSize > project.databaseLimit) {
return next(
new AppError(403, "Database limit exceeded.")
);
}
}
const result = await Model.insertMany(validData, { ordered: true });
if (!project.resources.db.isExternal) {
await Project.updateOne(
{ _id: project._id },
{ $inc: { databaseUsed: totalDocSize } }
);
}
return res.status(201).json({
success: true,
data: {
insertedCount: result.length,
},
message: "Bulk insert successful",
});
} catch (err) {
if (process.env.NODE_ENV !== 'test') {
console.error(err);
}
if (isDuplicateKeyError(err)) {
return next(
new AppError(409, "Duplicate value violates unique constraint.")
);
}
return next(new AppError(500, "Failed to insert bulk data"));
}
};
// GET ALL DATA
module.exports.getAllData = async (req, res, next) => {
try {
let start;
if (isDebug) start = performance.now();
const { collectionName } = req.params;
const project = req.project;
const collectionConfig = project.collections.find(
(c) => c.name === collectionName,
);
if (!collectionConfig)
return next(new AppError(404, "Collection not found"));
const connection = await getConnection(project._id);
const Model = getCompiledModel(
connection,
collectionConfig,
project._id,
project.resources.db.isExternal,
);
const baseFilter = req.rlsFilter && typeof req.rlsFilter === 'object' ? req.rlsFilter : {};
if (req.query.count === 'true') {
const countEngine = new QueryEngine(Model.find(), req.query);
const mongoFilter = countEngine._buildMongoQuery(true);
const mergedFilter = Object.keys(baseFilter).length > 0
? { $and: [mongoFilter, baseFilter] }
: mongoFilter;
const countQuery = Model.countDocuments(mergedFilter);
if (countEngine.hasRegexFilter && countQuery && typeof countQuery.maxTimeMS === 'function') {
countQuery.maxTimeMS(QueryEngine.REGEX_MAX_TIME_MS);
}
const count = await countQuery;
return new ApiResponse({ count }, "Count fetched successfully.").send(res, 200);
}
const features = new QueryEngine(Model.find(), req.query).filter();
if (Object.keys(baseFilter).length > 0) {
features.query = features.query.and([baseFilter]);
}
features.sort().limitFields().populate();
const total = await features.count();
const parsedLimit = parseInt(req.query.limit, 10);
const limit = Math.max(1, Math.min(Number.isNaN(parsedLimit) ? 100 : parsedLimit, 1000));
const useCursor = !!req.query.cursor;
if (useCursor) {
features.cursorPaginate();
} else {
features.paginate();
}
const data = await features.query.lean();
let items = data;
let nextCursor = null;
if (useCursor) {
features.generateNextCursor(data, limit);
items = data.slice(0, limit);
nextCursor = features.nextCursor;
}
if (isDebug) console.log(`[DEBUG] getall took ${(performance.now() - start).toFixed(2)}ms`);
const responseMeta = useCursor
? {
total,
cursor: req.query.cursor || null,
nextCursor,
limit,
}
: {
total,
page: parseInt(req.query.page, 10) || 1,
limit,
};
return new ApiResponse({
items,
...responseMeta,
}, "Data fetched successfully").send(res, 200);
} catch (err) {
if (process.env.NODE_ENV !== 'test') {
console.error(err);
}
if (err && (err.statusCode === 400 || err.name === 'QueryFilterError')) {
return next(new AppError(400, err.message || "Invalid query filter.", "Query Filter Error"));
}
return next(new AppError(500, "Failed to fetch data."));
}
};
// GET SINGLE DOC
module.exports.getSingleDoc = async (req, res, next) => {
try {
const { collectionName, id } = req.params;
const project = req.project;
if (!isValidId(id))
return next(new AppError(400, "Invalid ID format."));
const collectionConfig = project.collections.find(
(c) => c.name === collectionName,
);
if (!collectionConfig)
return next(new AppError(404, "Collection not found"));
const connection = await getConnection(project._id);
const Model = getCompiledModel(
connection,
collectionConfig,
project._id,
project.resources.db.isExternal,
);
const baseFilter = req.rlsFilter && typeof req.rlsFilter === 'object' ? req.rlsFilter : {};
// Soft delete filter
const includeDeleted = req.query.include_deleted === 'true';
const softDeleteFilter = includeDeleted ? {} : { isDeleted: { $ne: true } };
let query = Model.findOne({ $and: [{ _id: id }, baseFilter, softDeleteFilter] });
if (req.query.fields) {
query = query.select(req.query.fields.split(',').join(' '));
} else {
query = query.select('-__v');
}
if (req.query.meta === 'false') {
query = query.select('-schemaVersion -createdAt -updatedAt -__v');
}
const rawPopulateParam = req.query.populate || req.query.expand;
if (rawPopulateParam) {
const populateParam = Array.isArray(rawPopulateParam)
? rawPopulateParam.join(',')
: String(rawPopulateParam);
const fields = populateParam.split(',').map(f => f.trim()).filter(Boolean);
fields.forEach(f => {
query = query.populate({
path: f,
match: includeDeleted ? {} : { isDeleted: { $ne: true } }
});
});
}
const doc = await query.lean();
if (!doc) return next(new AppError(404, "Document not found."));
return new ApiResponse(doc).send(res, 200);
} catch (err) {
if (process.env.NODE_ENV !== 'test') {
console.error(err);
}
return next(new AppError(500, "An error occurred while processing your request"));
}
};
// AGGREGATE DATA
module.exports.aggregateData = async (req, res, next) => {
try {
let start;
if (isDebug) start = performance.now();
const { collectionName } = req.params;
const project = req.project;
const collectionConfig = project.collections.find(
(c) => c.name === collectionName,
);
if (!collectionConfig) {
return next(new AppError(404, "Collection not found"));
}
const { pipeline } = aggregateSchema.parse(req.body || {});
if (containsBlockedAggregationStage(pipeline)) {
return next(new AppError(400, "Aggregation pipeline contains blocked stage.", "Validation Error"));
}
const connection = await getConnection(project._id);
const Model = getCompiledModel(
connection,
collectionConfig,
project._id,
project.resources.db.isExternal,
);
const baseFilter =
req.rlsFilter && typeof req.rlsFilter === "object" ? req.rlsFilter : {};
const includeDeleted = req.query?.include_deleted === 'true';
const softDeleteFilter = includeDeleted ? {} : { isDeleted: { $ne: true } };
const filter = { ...baseFilter, ...softDeleteFilter };
// $geoNear and $search must be the first stage in the pipeline if present
let effectivePipeline = [];
const firstStage = pipeline.length > 0 ? Object.keys(pipeline[0])[0] : null;
if (firstStage === '$geoNear' || firstStage === '$search') {
effectivePipeline = [
pipeline[0],
{ $match: filter },
...pipeline.slice(1)
];
} else {
effectivePipeline = [
{ $match: filter },
...pipeline
];
}
const data = await Model.aggregate(effectivePipeline);
if (isDebug) console.log(`[DEBUG] aggregate took ${(performance.now() - start).toFixed(2)}ms`);
return new ApiResponse(data, "Aggregation executed successfully.").send(res, 200);
} catch (err) {
if (process.env.NODE_ENV !== 'test') {
console.error(err);
}
if (err instanceof z.ZodError) {
return next(new AppError(400, err.issues?.[0]?.message || "Invalid aggregation payload.", "Validation Error"));
}
return next(new AppError(500, "Failed to execute aggregation."));
}
};
// UPDATE DATA
module.exports.updateSingleData = async (req, res, next) => {
try {
const { collectionName, id } = req.params;
const project = req.project;
const incomingData = req.body;
if (!isValidId(id))
return next(new AppError(400, "Invalid ID format."));
const collectionConfig = project.collections.find(
(c) => c.name === collectionName,
);
if (!collectionConfig)
return next(new AppError(404, "Collection not found"));
const connection = await getConnection(project._id);
const Model = getCompiledModel(
connection,
collectionConfig,
project._id,
project.resources.db.isExternal,
);
const schemaRules = collectionConfig.model;
const { error: validationError, updateData } = validateUpdateData(
incomingData,
schemaRules,
);
if (validationError)
return next(new AppError(400, validationError));
// Prevent manual injection of soft-delete fields
delete updateData.isDeleted;
delete updateData.deletedAt;
const sanitizedData = sanitize(updateData);
const baseFilter = req.rlsFilter && typeof req.rlsFilter === 'object' ? req.rlsFilter : {};
const queryFilter = { $and: [{ _id: id }, { isDeleted: { $ne: true } }, baseFilter] };
let result;
// Only enforce quota for internal databases
if (!project.resources.db.isExternal) {
// 1. Fetch existing doc securely
const existingDoc = await Model.findOne(queryFilter).lean();
if (!existingDoc) {
return next(new AppError(404, "Document not found."));
}
// 2. Calculate sizes
const oldSize = mongoose.mongo.BSON.calculateObjectSize(existingDoc);
const simulatedNewDoc = { ...existingDoc, ...sanitizedData };
const newSize = mongoose.mongo.BSON.calculateObjectSize(simulatedNewDoc);
const sizeDelta = newSize - oldSize;
// 3. Enforce quota if size is increasing
if (sizeDelta > 0) {
if ((project.databaseUsed || 0) + sizeDelta > project.databaseLimit) {
return next(new AppError(403, "Storage quota exceeded. Please upgrade your plan."));
}
}
// 4. Update the document
result = await Model.findOneAndUpdate(
queryFilter,
{ $set: sanitizedData },
{ new: true, runValidators: true },
).lean();
// 5. Apply the delta (positive or negative) atomically
await Project.findByIdAndUpdate(
project._id,
{ $inc: { databaseUsed: sizeDelta } }
);
} else {
// External DB Flow (No quota checks)
result = await Model.findOneAndUpdate(
queryFilter,
{ $set: sanitizedData },
{ new: true, runValidators: true },
).lean();
if (!result) return next(new AppError(404, "Document not found."));
}
await webhookQueue.add('trigger-webhook', {
projectId: project._id,
event: 'document.updated',
collection: collectionName,
payload: result
}, { removeOnComplete: true });
return new ApiResponse(result, "Updated").send(res, 200);
} catch (err) {
if (process.env.NODE_ENV !== 'test') {
console.error(err);
}
if (isDuplicateKeyError(err)) {
return next(new AppError(409, "Duplicate value violates unique constraint."));
}
return next(new AppError(500, "An error occurred while processing your request"));
}
};
/**
* Soft-deletes a single document by its ID (moves it to trash).
* @param {import('express').Request} req - Express request object.
* @param {import('express').Response} res - Express response object.
*/
module.exports.deleteSingleDoc = async (req, res, next) => {
try {
const { collectionName, id } = req.params;
const project = req.project;
if (!isValidId(id))
return next(new AppError(400, "Invalid ID format."));
const collectionConfig = project.collections.find(
(c) => c.name === collectionName,
);
if (!collectionConfig)
return next(new AppError(404, "Collection not found"));
const connection = await getConnection(project._id);
const Model = getCompiledModel(
connection,
collectionConfig,
project._id,
project.resources.db.isExternal,
);
const result = await Model.findOneAndUpdate(
{ _id: id, isDeleted: { $ne: true }, ...(req.rlsFilter || {}) },
{
$set: {
isDeleted: true,
deletedAt: new Date()
}
},
{ new: false } // return the original document for webhook
).lean();
if (!result)
return next(new AppError(404, "Document not found."));
// We don't decrement databaseUsed here because the document still occupies space.
// It will be decremented during hard delete in the background worker.
try {
await enqueueCollectionCleanup(project._id, collectionName);
} catch (err) {
console.error("Failed to enqueue trash cleanup job", { projectId: String(project._id), collectionName, err });
}
await webhookQueue.add('trigger-webhook', {
projectId: project._id,
event: 'document.deleted',
collection: collectionName,
payload: result
}, { removeOnComplete: true });
return new ApiResponse({ id }, "Document moved to trash").send(res, 200);
} catch (err) {
if (process.env.NODE_ENV !== 'test') {
console.error(err);
}
return next(new AppError(500, "An error occurred while processing your request"));
}
};
/**
* Recovers a single soft-deleted document from trash.
* @param {import('express').Request} req - Express request object.
* @param {import('express').Response} res - Express response object.
* @param {import('express').NextFunction} next - Express next function.
*/
module.exports.recoverSingleDoc = async (req, res, next) => {
try {
const { collectionName, id } = req.params;
const project = req.project;
if (!isValidId(id)) {
return next(new AppError(400, "Invalid document ID format."));
}
const collectionConfig = project.collections.find(
(c) => c.name === collectionName,
);
if (!collectionConfig) {
return next(new AppError(404, "Collection not found"));
}
const connection = await getConnection(project._id);
const Model = getCompiledModel(
connection,
collectionConfig,
project._id,
project.resources.db.isExternal,
);
const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
const result = await Model.findOneAndUpdate(
{
_id: id,
isDeleted: true,
deletedAt: { $gte: thirtyDaysAgo },
...(req.rlsFilter || {})
},
{
$set: {
isDeleted: false,
deletedAt: null
}
},
{ new: true }
).lean();
if (!result) {
return next(new AppError(404, "Document not found or recovery window expired (30 days)."));
}
await webhookQueue.add('trigger-webhook', {
projectId: project._id,
event: 'document.recovered',
collection: collectionName,
payload: result
}, { removeOnComplete: true });
try {
await syncCollectionCleanup(project._id, collectionName);
} catch (err) {
console.error("Failed to sync trash cleanup job after recovery", { projectId: String(project._id), collectionName, err });
}
return new ApiResponse(result, "Document recovered from trash").send(res, 200);
} catch (err) {
if (process.env.NODE_ENV !== 'test') {
console.error(err);
}
if (isDuplicateKeyError(err)) {
return next(new AppError(409, "Cannot restore document: a unique field value conflicts with an existing active document."));
}
return next(new AppError(500, "Failed to recover document."));
}
};