Spaces:
Sleeping
Sleeping
File size: 4,502 Bytes
97f53b4 |
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 |
const express = require("express");
const router = express.Router();
var Banner = require('../Database/models/banner');
const mongoose = require("mongoose");
const multer = require('multer');
const firebase = require("../utils/firebase")
var imageUrl = ""
//Disk storage where image store
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './uploads');
},
filename: function (req, file, cb) {
cb(null, file.originalname);
}
});
//Check the image formate
const fileFilter = (req, file, cb) => {
// reject a file
if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png' || file.mimetype === 'image/jpg') {
cb(null, true);
} else {
cb(null, false);
}
};
const upload = multer({
storage: storage,
limits: {
fileSize: 1024 * 1024 * 5
},
fileFilter: fileFilter
});
router.post("/", upload.any(), async (req, res) => {
console.log(req.body); // Log non-file data
const uploadedFiles = req.files; // Uploaded files
let bannerImage = ""
let bannerImageName = uploadedFiles.find(
(f) => f.fieldname.includes('banner')
);
if (bannerImageName != "" && bannerImageName != undefined) {
let bannerImagePath = uploadedFiles.find(
(f) => f.path.includes('banner')
);
await firebase.uploadFile(bannerImagePath, "bannerImage/" + bannerImageName);
// Generating signed URL for the uploaded image
await firebase.generateSignedUrl("bannerImage/" + bannerImageName)
.then((url) => {
imageUrl = url;
})
.catch((err) => {
console.error(`Error generating signed URL for ${fileName.filename}:`, err);
return res.status(500).json({ error: 'Error generating image URL.' });
});
}
try {
const { name, percentage, products } = req.body; // Non-file data
const bannerProducts = [];
let imageUrl = ''; // Declare imageUrl variable
for (let i = 0; i < products.length; i++) {
const product = products[i]; // Directly use product if it's already an object
const fileName = uploadedFiles.find(
(f) => f.fieldname === `products[${i}][image]`
);
// If no file is found for the product, skip
if (!fileName) {
console.log(`No image found for product ${i}`);
continue;
}
const filePath = fileName.path;
// Upload file and generate the signed URL
await firebase.uploadFile(filePath, "bannerProducts/" + fileName.filename);
// Generating signed URL for the uploaded image
await firebase.generateSignedUrl("bannerProducts/" + fileName.filename)
.then((url) => {
imageUrl = url;
})
.catch((err) => {
console.error(`Error generating signed URL for ${fileName.filename}:`, err);
return res.status(500).json({ error: 'Error generating image URL.' });
});
bannerProducts.push({
_id: new mongoose.Types.ObjectId(),
name: product.name,
image: imageUrl,
price: product.price,
});
}
const banner = new Banner({
_id: new mongoose.Types.ObjectId(),
name,
percentage,
bannerImage,
products: bannerProducts,
});
const savedBanner = await banner.save();
res.status(201).json({ message: 'Banner created successfully', savedBanner });
} catch (error) {
console.error('Error in creating banner:', error);
res.status(500).json({ error: error.message });
}
});
router.get("/", function (req, res) {
Banner.find()
.exec()
.then((data) => {
console.log(data)
try {
const response = {
count: data.length,
products: data
};
res.status(200).json(response);
} catch (e) {
res.status(400).json({
error: e
});
}
})
.catch((error) => {
res.status(400).json({
error: error
});
})
});
module.exports = router;
|