Skip to content

Commit 27641c0

Browse files
committed
Formatting fixes (No code change)
1 parent 9b21597 commit 27641c0

File tree

5 files changed

+214
-218
lines changed

5 files changed

+214
-218
lines changed

src/db.js

+3-3
Original file line numberDiff line numberDiff line change
@@ -38,15 +38,15 @@ module.exports = (() => {
3838
_createdOn: Date, // Date on which its created
3939
_apiKey: { type: String, index: true, select: false }, // API KEY used to create / update the record
4040
_updatedOn: Date, // Date on which its updated
41-
_expiry: { type: Date, select: false}, // date after which this record will be deleted
41+
_expiry: { type: Date, select: false }, // date after which this record will be deleted
4242
data: { type: Object } // Actual data of the record
4343
});
4444

4545
// Once switched on the index will be be set in mongodb. Might need to remove it in order to switch off the behaviour
46-
if(config.ENABLE_DATA_EXPIRY){
46+
if (config.ENABLE_DATA_EXPIRY) {
4747
dataSchema.index({ "_expiry": 1 }, { expireAfterSeconds: 0 });
4848
}
49-
49+
5050
return mongoose.model('Data', dataSchema);
5151
};
5252

src/model.js

+9-12
Original file line numberDiff line numberDiff line change
@@ -68,14 +68,11 @@ const xput = async (req, res, next) => {
6868
try {
6969
const record = await Data.findOne({ _id: req.recordId, _box: req.box }).exec();
7070
if (record) {
71-
await Data.updateOne(
72-
{ _id: req.recordId, _box: req.box },
73-
{
74-
_updatedOn: new Date(),
75-
_expiry: helper.getExpiryDate(),
76-
data: req.body
77-
}
78-
);
71+
await Data.updateOne({ _id: req.recordId, _box: req.box }, {
72+
_updatedOn: new Date(),
73+
_expiry: helper.getExpiryDate(),
74+
data: req.body
75+
});
7976
res.json({ message: 'Record updated.' });
8077
} else {
8178
res.status(400).json({ message: 'Invalid record Id' });
@@ -115,11 +112,11 @@ const xmeta = async (req, res, next) => {
115112
const promises = [
116113
Data.countDocuments(query).exec(),
117114
Data.findOne(query)
118-
.sort('_createdOn')
119-
.exec(),
115+
.sort('_createdOn')
116+
.exec(),
120117
Data.findOne(query)
121-
.sort('-_updatedOn')
122-
.exec()
118+
.sort('-_updatedOn')
119+
.exec()
123120
];
124121

125122
const result = {};

src/routes.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,8 @@ router.delete("/*", model.xdelete);
2525
* DATA endpoint's common error handling middleware
2626
*/
2727
router.use((err, req, res, next) => {
28-
console.error(err);
29-
res.status(err.statusCode || 500).json({ message: err.message });
28+
console.error(err);
29+
res.status(err.statusCode || 500).json({ message: err.message });
3030
});
3131

3232
module.exports = router;

src/validators.js

+88-88
Original file line numberDiff line numberDiff line change
@@ -5,123 +5,123 @@ const Data = require("./db").getInstance();
55

66
// remove the system keys from req.body
77
const removeNativeKeys = (req, res, next) => {
8-
delete req.body._id;
9-
delete req.body._createdOn;
10-
delete req.body._updatedOn;
11-
delete req.body._collection;
12-
next();
8+
delete req.body._id;
9+
delete req.body._createdOn;
10+
delete req.body._updatedOn;
11+
delete req.body._collection;
12+
next();
1313
};
1414

1515
// validator: size of payload should be < 10KB
1616
const sizeValidator = (req, res, next) => {
17-
if (req.method === "POST" || req.method === "PUT") {
18-
if (Object.keys(req.body).length > 0) {
19-
const memorySize = helper.memorySizeOf(req.body);
20-
req["bodySize"] = memorySize;
21-
22-
// memorySize is size in bytes. 10KB => 10 * 1024
23-
if (memorySize > config.SIZE_LIMIT * 1024) {
24-
throwError(`JSON body is too large. Should be less than ${config.SIZE_LIMIT}KB`, 413);
25-
} else if (Array.isArray(req.body)) {
26-
if (req.body.length > 1000) {
27-
throwError("Not more than 1000 records for bulk upload.", 413);
28-
} else next();
29-
} else next();
30-
} else throwError("Empty body.", 400);
31-
} else next();
17+
if (req.method === "POST" || req.method === "PUT") {
18+
if (Object.keys(req.body).length > 0) {
19+
const memorySize = helper.memorySizeOf(req.body);
20+
req["bodySize"] = memorySize;
21+
22+
// memorySize is size in bytes. 10KB => 10 * 1024
23+
if (memorySize > config.SIZE_LIMIT * 1024) {
24+
throwError(`JSON body is too large. Should be less than ${config.SIZE_LIMIT}KB`, 413);
25+
} else if (Array.isArray(req.body)) {
26+
if (req.body.length > 1000) {
27+
throwError("Not more than 1000 records for bulk upload.", 413);
28+
} else next();
29+
} else next();
30+
} else throwError("Empty body.", 400);
31+
} else next();
3232
};
3333

3434
// The Body top level keys should start with an alphabet
3535
const keysValidator = (req, res, next) => {
36-
let validKeys = Array.isArray(req.body) ? req.body.every(helper.isValidKeys) : helper.isValidKeys(req.body);
37-
if (validKeys) next();
38-
else throwError("Invalid JSON keys. Keys should start with an alphabet");
36+
let validKeys = Array.isArray(req.body) ? req.body.every(helper.isValidKeys) : helper.isValidKeys(req.body);
37+
if (validKeys) next();
38+
else throwError("Invalid JSON keys. Keys should start with an alphabet");
3939
};
4040

4141
// extract the box, collection, record ids from the path
4242
const extractParams = (req, res, next) => {
43-
const path = req.path;
44-
const pathParams = path.split("/").filter((p) => !!p);
45-
const isHexString = /^([0-9A-Fa-f]){24}$/;
46-
const isValidBoxID = /^[0-9A-Za-z_]+$/i;
43+
const path = req.path;
44+
const pathParams = path.split("/").filter((p) => !!p);
45+
const isHexString = /^([0-9A-Fa-f]){24}$/;
46+
const isValidBoxID = /^[0-9A-Za-z_]+$/i;
4747

48-
req["apiKey"] =
49-
req.headers["x-api-key"] || (req.headers["authorization"] ? req.headers["authorization"].split(" ")[1] : null);
48+
req["apiKey"] =
49+
req.headers["x-api-key"] || (req.headers["authorization"] ? req.headers["authorization"].split(" ")[1] : null);
5050

51-
if (pathParams[0]) {
52-
req["box"] = isValidBoxID.test(pathParams[0]) ? pathParams[0] : undefined;
51+
if (pathParams[0]) {
52+
req["box"] = isValidBoxID.test(pathParams[0]) ? pathParams[0] : undefined;
5353

54-
if (pathParams[1]) {
55-
const isObjectId = isHexString.test(pathParams[1]);
56-
if (isObjectId) req["recordId"] = pathParams[1];
57-
else req["collection"] = isValidBoxID.test(pathParams[1]) ? pathParams[1] : undefined;
58-
}
54+
if (pathParams[1]) {
55+
const isObjectId = isHexString.test(pathParams[1]);
56+
if (isObjectId) req["recordId"] = pathParams[1];
57+
else req["collection"] = isValidBoxID.test(pathParams[1]) ? pathParams[1] : undefined;
58+
}
5959

60-
if (!req["recordId"] && pathParams[2]) {
61-
req["recordId"] = isHexString.test(pathParams[2]) ? pathParams[2] : undefined;
62-
}
60+
if (!req["recordId"] && pathParams[2]) {
61+
req["recordId"] = isHexString.test(pathParams[2]) ? pathParams[2] : undefined;
62+
}
6363

64-
next();
65-
} else throwError("Box id cannot be empty.");
64+
next();
65+
} else throwError("Box id cannot be empty.");
6666
};
6767

6868
// check if all the required parameters is present
6969
const validateParams = (req, res, next) => {
70-
const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
71-
72-
if (!req.box) {
73-
throwError("Invalid or empty box id");
74-
} else if (req.box.length < 20 || req.box.length > 64) {
75-
throwError("Box id must be atleast 20 chars long & max. 64 chars.");
76-
} else if (req.collection ? req.collection.length > 20 : false) {
77-
throwError("Collection name can't be more than 20 chars.");
78-
} else if (req.method === "PUT" || req.method === "DELETE") {
79-
if (!req.recordId && !req.query.q) {
80-
throwError("Invalid or empty record id or missing query definition");
81-
} else if (Array.isArray(req.body)) {
82-
throwError("Bulk update not supported.");
83-
} else next();
84-
} else if (req.apiKey) {
85-
if (uuidRegex.test(req["apiKey"])) next();
86-
else throwError("Invalid API-KEY. API-KEY Should be a UUID.");
87-
} else next();
70+
const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
71+
72+
if (!req.box) {
73+
throwError("Invalid or empty box id");
74+
} else if (req.box.length < 20 || req.box.length > 64) {
75+
throwError("Box id must be atleast 20 chars long & max. 64 chars.");
76+
} else if (req.collection ? req.collection.length > 20 : false) {
77+
throwError("Collection name can't be more than 20 chars.");
78+
} else if (req.method === "PUT" || req.method === "DELETE") {
79+
if (!req.recordId && !req.query.q) {
80+
throwError("Invalid or empty record id or missing query definition");
81+
} else if (Array.isArray(req.body)) {
82+
throwError("Bulk update not supported.");
83+
} else next();
84+
} else if (req.apiKey) {
85+
if (uuidRegex.test(req["apiKey"])) next();
86+
else throwError("Invalid API-KEY. API-KEY Should be a UUID.");
87+
} else next();
8888
};
8989

9090
// Check if the Request has a valid API_KEY
9191
const authenticateRequest = async (req, res, next) => {
92-
try {
93-
if (req.method === "POST" || req.method === "PUT" || req.method === "DELETE") {
94-
const firstRecord = await Data.findOne({ _box: req.box })
95-
.select("_apiKey")
96-
.sort("-_createdOn")
97-
.exec();
98-
if (firstRecord) {
99-
if (firstRecord._apiKey) {
100-
if (firstRecord._apiKey == req["apiKey"]) next();
101-
else throwError("Invalid API_KEY.", 401);
102-
} else {
103-
// dont pass API_KEY if the first data does not have key
104-
req["apiKey"] = null;
105-
next();
106-
}
107-
} else next();
108-
} else next();
109-
} catch (error) {
110-
next(error);
111-
}
92+
try {
93+
if (req.method === "POST" || req.method === "PUT" || req.method === "DELETE") {
94+
const firstRecord = await Data.findOne({ _box: req.box })
95+
.select("_apiKey")
96+
.sort("-_createdOn")
97+
.exec();
98+
if (firstRecord) {
99+
if (firstRecord._apiKey) {
100+
if (firstRecord._apiKey == req["apiKey"]) next();
101+
else throwError("Invalid API_KEY.", 401);
102+
} else {
103+
// dont pass API_KEY if the first data does not have key
104+
req["apiKey"] = null;
105+
next();
106+
}
107+
} else next();
108+
} else next();
109+
} catch (error) {
110+
next(error);
111+
}
112112
};
113113

114114
const throwError = (message, code = 400) => {
115-
const errorObject = new Error(message);
116-
errorObject.statusCode = code;
117-
throw errorObject;
115+
const errorObject = new Error(message);
116+
errorObject.statusCode = code;
117+
throw errorObject;
118118
};
119119

120120
module.exports = {
121-
removeNativeKeys,
122-
sizeValidator,
123-
keysValidator,
124-
extractParams,
125-
validateParams,
126-
authenticateRequest,
121+
removeNativeKeys,
122+
sizeValidator,
123+
keysValidator,
124+
extractParams,
125+
validateParams,
126+
authenticateRequest,
127127
};

0 commit comments

Comments
 (0)