I am trying to improve the performance of my application by saving images from an API response to a MongoDB database for future use, instead of making repeated requests.
Currently, I have implemented a system where I retrieve the image path from the API and use fs.createWriteStream() to save the file. However, when I try to create a "Character" using this saved image, only a portion of the image is being saved before the code moves on to the next step.
I have attempted to make the function asynchronous and used await before making the URL request. I also tried alternative methods like writeFileSync(), but with no success.
Is there a way to ensure that the entire image file is fully written to disk before continuing with the MongoDB update?
let imagePath = req.body.characterObject.thumbnail.path + '.' + req.body.characterObject.thumbnail.extension;
let superPath = './uploads/marvelousImage.jpg';
let marvelousImage;
axios({
url: imagePath,
responseType: 'stream',
})
.then(response => {
marvelousImage = response.data.pipe(fs.createWriteStream(superPath));
})
.catch(err => {
console.log(err)
});
User.findOne({ "username": "administrator"})
.then(user => {
let characterId = req.body.characterObject.id;
for(let i = 0; i < user.characters.length; i++) {
if(characterId == user.characters[i].id) {
return Promise.reject({
code: 422,
message: 'You already have this character!',
reason: "CharacterDuplicationError"
});
}
}
console.log(req.body.characterObject);
Character.create({
description: req.body.characterObject.description || 'bocho',
events: req.body.characterObject.events || 'lopo',
thumbnail: req.body.characterObject.thumbnail || 'goso',
name: req.body.characterObject.name || 'John Doe',
id: req.body.characterObject.id,
"image.data": fs.readFileSync(superPath),
"image.contentType": 'image/jpeg'
})
.then(char => {
console.log('lalala');
console.log(char);
user.characters.push(char);
user.save();
return res.status(201).json({message: "Character Added!"})
})
.catch(err => {
if(err.reason === "CharacterDuplicationError") {
return res.send(err);
}
})
})
});