Advertisement
Infernale

Untitled

Dec 8th, 2020
796
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.91 KB | None | 0 0
  1. function generateImgName(file_name) {
  2. const name = file_name.substring(0, file_name.lastIndexOf('.'))
  3. const ext = file_name.substring(file_name.lastIndexOf('.') + 1)
  4.  
  5. return `${name}_${Date.now()}.${ext}`
  6. }
  7.  
  8. function generateImgPath(name) {
  9. return `${__dirname}/../../client/public/uploads/${name}`
  10. }
  11.  
  12. function resizeAndSave(img, path) {
  13. sharp(img.data).resize(400, 300, {fit: 'fill'})
  14. .toFile(path)
  15. }
  16.  
  17. function preprocessImage(req) {
  18. try {
  19. // CASE 1: Multi file upload
  20. req.files.file.forEach(img => {
  21. // Preprocess String to get image name and extension
  22. name = generateImgName(img.name)
  23. path = generateImgPath(name)
  24.  
  25. // Push preprocessed image name to body before storing it to database
  26. req.body['images'].push({
  27. name: name,
  28. path: `/uploads/${name}`
  29. })
  30.  
  31.  
  32. // Resize image to 250 x 180 and save it
  33. resizeAndSave(img, path)
  34. })
  35. } catch(err) {
  36. // CASE 2: Single file upload
  37. img = req.files.file
  38.  
  39. name = generateImgName(img.name)
  40. path = generateImgPath(name)
  41.  
  42. req.body['images'].push({
  43. name: name,
  44. path: `/uploads/${name}`
  45. })
  46.  
  47. resizeAndSave(img, path)
  48. }
  49. }
  50.  
  51. router.post('/add', async (req, res) => {
  52. // Reverse JSON.stringify()
  53. req.body.specifications = JSON.parse(req.body.specifications)
  54. req.body['images'] = []
  55.  
  56. preprocessImage(req)
  57.  
  58. const newProduct = new Product(req.body)
  59.  
  60. try {
  61. const ProductItem = await newProduct.save()
  62. if(!ProductItem) {
  63. throw new Error('Fail to save product..')
  64. }
  65. res.status(200).json(ProductItem)
  66. } catch(err) {
  67. res.status(500).json({message: err.message})
  68. }
  69. })
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement