function generateImgName(file_name) {
const name = file_name.substring(0, file_name.lastIndexOf('.'))
const ext = file_name.substring(file_name.lastIndexOf('.') + 1)
return `${name}_${Date.now()}.${ext}`
}
function generateImgPath(name) {
return `${__dirname}/../../client/public/uploads/${name}`
}
function resizeAndSave(img, path) {
sharp(img.data).resize(400, 300, {fit: 'fill'})
.toFile(path)
}
function preprocessImage(req) {
try {
// CASE 1: Multi file upload
req.files.file.forEach(img => {
// Preprocess String to get image name and extension
name = generateImgName(img.name)
path = generateImgPath(name)
// Push preprocessed image name to body before storing it to database
req.body['images'].push({
name: name,
path: `/uploads/${name}`
})
// Resize image to 250 x 180 and save it
resizeAndSave(img, path)
})
} catch(err) {
// CASE 2: Single file upload
img = req.files.file
name = generateImgName(img.name)
path = generateImgPath(name)
req.body['images'].push({
name: name,
path: `/uploads/${name}`
})
resizeAndSave(img, path)
}
}
router.post('/add', async (req, res) => {
// Reverse JSON.stringify()
req.body.specifications = JSON.parse(req.body.specifications)
req.body['images'] = []
preprocessImage(req)
const newProduct = new Product(req.body)
try {
const ProductItem = await newProduct.save()
if(!ProductItem) {
throw new Error('Fail to save product..')
}
res.status(200).json(ProductItem)
} catch(err) {
res.status(500).json({message: err.message})
}
})