-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.js
More file actions
46 lines (44 loc) · 1.72 KB
/
middleware.js
File metadata and controls
46 lines (44 loc) · 1.72 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
const { v4: uuidv4 } = require('uuid');
const { CustomError } = require('./utils/CustomError');
const inventoryItemSchema = require('./model/inventory');
const warehouseSchema = require('./model/warehouse');
module.exports.validateInventoryItem = (req, res, next) => {
//Create a new object with id and the data from request body
const newInventoryItem = {
id: req.params.id ? req.params.id : uuidv4(),
...req.body,
status: Number(req.body.quantity) > 0 ? 'In Stock' : 'Out of Stock',
quantity: Number(req.body.quantity),
};
//Validated the newly created object
const { error, value } = inventoryItemSchema.validate(newInventoryItem, {
abortEarly: false,
});
//If the is validation error, throw error
if (error) {
const errorArray = error.details.map((errMsg) => errMsg.message).join(', ');
throw new CustomError(400, `Please provide valid inputs: ${errorArray}`);
}
//If the object passed validation, add the object to the request for controller to use it
req.validatedData = value;
next();
};
module.exports.validateWarehouse = (req, res, next) => {
//Create a new object with id and the data from request body
const newWarehouseItem = {
id: req.params.id ? req.params.id : uuidv4(),
...req.body,
};
//Validated the newly created object
const { error, value } = warehouseSchema.validate(newWarehouseItem, {
abortEarly: false,
});
//If the is validation error, throw error
if (error) {
const errorArray = error.details.map((errMsg) => errMsg.message).join(', ');
throw new CustomError(400, `Please provide valid inputs: ${errorArray}`);
}
//If the object passed validation, add the object to the request for controller to use it
req.validatedData = value;
next();
};