forked from geturbackend/urBackend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdata.controller.js
More file actions
250 lines (205 loc) · 6.9 KB
/
Copy pathdata.controller.js
File metadata and controls
250 lines (205 loc) · 6.9 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
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 } = require("@urbackend/common");
// Validate MongoDB ObjectId
const isValidId = (id) => mongoose.Types.ObjectId.isValid(id);
const isDuplicateKeyError = (err) => {
return err && err.code === 11000;
};
// INSERT DATA
module.exports.insertData = async (req, res) => {
try {
console.time("insert data");
const { collectionName } = req.params;
const project = req.project;
const collectionConfig = project.collections.find(
(c) => c.name === collectionName,
);
if (!collectionConfig)
return res.status(404).json({ error: "Collection not found" });
const schemaRules = collectionConfig.model;
const incomingData = req.body;
// Recursive validation for all field types
const { error, cleanData } = validateData(incomingData, schemaRules);
if (error) return res.status(400).json({ error });
const safeData = sanitize(cleanData);
let docSize = 0;
if (!project.resources.db.isExternal) {
docSize = Buffer.byteLength(JSON.stringify(safeData));
if ((project.databaseUsed || 0) + docSize > project.databaseLimit) {
return res.status(403).json({ error: "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 } },
);
}
console.timeEnd("insert data");
res.status(201).json(result);
} catch (err) {
console.error(err);
if (isDuplicateKeyError(err)) {
return res.status(409).json({
error: "Duplicate value violates unique constraint.",
details: err.message,
});
}
res.status(500).json({ error: err.message });
}
};
// GET ALL DATA
module.exports.getAllData = async (req, res) => {
try {
console.time("getall");
const { collectionName } = req.params;
const project = req.project;
const collectionConfig = project.collections.find(
(c) => c.name === collectionName,
);
if (!collectionConfig)
return res.status(404).json({ error: "Collection not found" });
const connection = await getConnection(project._id);
const Model = getCompiledModel(
connection,
collectionConfig,
project._id,
project.resources.db.isExternal,
);
const features = new QueryEngine(Model.find(), req.query)
.filter()
.sort()
.paginate();
const data = await features.query.lean();
console.timeEnd("getall");
res.json(data);
} catch (err) {
console.error(err);
res.status(500).json({ error: err.message });
}
};
// GET SINGLE DOC
module.exports.getSingleDoc = async (req, res) => {
try {
const { collectionName, id } = req.params;
const project = req.project;
// ensure valid mongose objct id
if (!isValidId(id))
return res.status(400).json({ error: "Invalid ID format." });
const collectionConfig = project.collections.find(
(c) => c.name === collectionName,
);
if (!collectionConfig)
return res.status(404).json({ error: "Collection not found" });
const connection = await getConnection(project._id);
const Model = getCompiledModel(
connection,
collectionConfig,
project._id,
project.resources.db.isExternal,
);
const doc = await Model.findById(id).lean();
if (!doc) return res.status(404).json({ error: "Document not found." });
res.json(doc);
} catch (err) {
console.error(err);
res.status(500).json({ error: err.message });
}
};
// UPDATE DATA
module.exports.updateSingleData = async (req, res) => {
try {
const { collectionName, id } = req.params;
const project = req.project;
const incomingData = req.body;
if (!isValidId(id))
return res.status(400).json({ error: "Invalid ID format." });
const collectionConfig = project.collections.find(
(c) => c.name === collectionName,
);
if (!collectionConfig)
return res.status(404).json({ error: "Collection not found" });
const connection = await getConnection(project._id);
const Model = getCompiledModel(
connection,
collectionConfig,
project._id,
project.resources.db.isExternal,
);
// Recursive validation for all field types
const schemaRules = collectionConfig.model;
const { error: validationError, updateData } = validateUpdateData(
incomingData,
schemaRules,
);
if (validationError)
return res.status(400).json({ error: validationError });
const sanitizedData = sanitize(updateData);
const result = await Model.findByIdAndUpdate(
id,
{ $set: sanitizedData },
{ new: true, runValidators: true },
).lean();
if (!result) return res.status(404).json({ error: "Document not found." });
res.json({ message: "Updated", data: result });
} catch (err) {
console.error(err);
if (isDuplicateKeyError(err)) {
return res.status(409).json({
error: "Duplicate value violates unique constraint.",
details: err.message,
});
}
res.status(500).json({ error: err.message });
}
};
// DELETE DATA
module.exports.deleteSingleDoc = async (req, res) => {
try {
const { collectionName, id } = req.params;
const project = req.project;
if (!isValidId(id))
return res.status(400).json({ error: "Invalid ID format." });
const collectionConfig = project.collections.find(
(c) => c.name === collectionName,
);
if (!collectionConfig)
return res.status(404).json({ error: "Collection not found" });
const connection = await getConnection(project._id);
const Model = getCompiledModel(
connection,
collectionConfig,
project._id,
project.resources.db.isExternal,
);
const docToDelete = await Model.findById(id);
if (!docToDelete)
return res.status(404).json({ error: "Document not found." });
let docSize = 0;
if (!project.resources.db.isExternal) {
docSize = Buffer.byteLength(JSON.stringify(docToDelete));
}
await Model.deleteOne({ _id: id });
if (!project.resources.db.isExternal) {
let databaseUsed = Math.max(0, (project.databaseUsed || 0) - docSize);
await Project.updateOne({ _id: project._id }, { $set: { databaseUsed } });
}
res.json({ message: "Document deleted", id });
} catch (err) {
console.error(err);
res.status(500).json({ error: err.message });
}
};