OpenClassrooms devient une université américaine accréditée.
Découvrez ce que cela change pour vousTable des matières
- Partie 1
Build a Simple Express Server
- Partie 2
Build a RESTful API
- Partie 3
Make Your API Secure
- Partie 4
Add Image Upload to Your API
Expand the Back End's Delete Function
#Modify the DELETE Route
As a final touch to the file handling in your back end, make sure that whenever a Thing is deleted from the database, the corresponding image file also gets deleted.
In your stuff controller, import the Node fs package:
const fs = require('fs');
Now you can modify your deleteThing() function:
exports.deleteThing = (req, res, next) => {
Thing.findOne({_id: req.params.id}).then(
(thing) => {
const filename = thing.imageUrl.split('/images/')[1];
fs.unlink('images/' + filename, () => {
Thing.deleteOne({_id: req.params.id}).then(
() => {
res.status(200).json({
message: 'Deleted!'
});
}
).catch(
(error) => {
res.status(400).json({
error: error
});
}
);
});
}
);
};
In this function:
Use the ID you receive as a parameter to access the corresponding
Thingin the database.Use the fact that you know there is an
/images/segment in your image URL to separate the file name.Then use the
fspackage'sunlinkfunction to delete that file, passing it the file to be deleted and the callback to be executed once that file has been deleted.In the callback, implement the original logic, deleting the
Thingfrom the database.
Your API can now successfully handle all CRUD operations containing files: when a user creates a new Thing , updates an existing Thing , or deletes a Thing !
#Let's Recap!
The built-in
fspackage exposes methods for interacting with the server's file system.fs'
unlink()method lets you delete a file from the file system.
#What You've Learned in This Course
You're nearly finished. Well done!
Let's have a look at what you've learned:
- Formations jusqu’à 100 % financées
- Date de début flexible
- Projets professionnalisants
- Mentorat individuel