Created
October 27, 2024 10:52
-
-
Save Salman18/14824a1e60af37f10e5d16d9bf47eba0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import models from '../models'; | |
import path from 'path'; | |
import fs from 'fs'; | |
import axios from 'axios'; // Import axios | |
import FormData from 'form-data'; // Import the form-data package | |
import { Op } from 'sequelize'; // Import Op from sequelize | |
// Function to upload a single image to S3 | |
const uploadSingleImage = async (imagePath: fs.PathLike) => { | |
const formData = new FormData(); | |
formData.append('image', fs.createReadStream(imagePath)); // Use form-data to append the image | |
// Send a POST request using axios | |
const response = await axios.post('http://localhost:4000/api/v1/admin/upload/single', formData, { | |
headers: { | |
...formData.getHeaders(), // Important to set headers for form-data | |
}, | |
}); | |
// Return the URL from the response | |
return response.data.url; | |
}; | |
// Function to update thumbnail URLs in the database | |
const updateThumbnailUrls = async (localFolderPath: string) => { | |
try { | |
console.log('Connection has been established successfully.'); | |
// Fetch all subcategories | |
// const subcategories = await models.Subcategory.findAll(); | |
const brands = await models.Brand.findAll(); | |
// Read all image files from the local folder | |
const imageFiles = fs.readdirSync(localFolderPath).filter(file => { | |
// Filter to include only .jpg or .png files (adjust as necessary) | |
return file.endsWith('.jpg') || file.endsWith('.png'); | |
}); | |
for (const brand of brands) { | |
const { name } = brand; | |
const matchingImage = imageFiles.find(file => { | |
const imageBaseName = path.basename(file, path.extname(file)); | |
return imageBaseName === name; | |
}); | |
if (matchingImage) { | |
const imagePath = path.join(localFolderPath, matchingImage); | |
console.log(`Found image for ${name}: ${imagePath}`); | |
// Upload image to S3 and get the URL | |
const imageUrl = await uploadSingleImage(imagePath); | |
console.log(`Image uploaded successfully. URL: ${imageUrl}`); | |
await models.Brand.update( | |
{ logo_url: imageUrl }, | |
{ where: { name: name } } // Update based on the first word | |
); | |
console.log(`Thumbnail URL updated in database for ${name}.`); | |
} else { | |
console.log(`No matching image found for ${name}.`); | |
} | |
} | |
} catch (error) { | |
console.error('Error updating thumbnail URLs:', error); | |
} | |
}; | |
export default updateThumbnailUrls; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment