Skip to content

Commit

Permalink
Add file deletion from bucket
Browse files Browse the repository at this point in the history
  • Loading branch information
suggoitanoshi committed Jul 3, 2021
1 parent 464e6aa commit 32cebc2
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 3 deletions.
10 changes: 9 additions & 1 deletion app/controllers/materiController.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const { Materi, File } = require('../database/models');
const { uploadFile } = require('../helper/uploader');
const { uploadFile, deleteFile } = require('../helper/uploader');
const { parseForm } = require('../helper/parseform');

module.exports = {
Expand Down Expand Up @@ -51,9 +51,17 @@ module.exports = {
*/
async removeMateri(req, res){
const id = req.params.id;
const materi = await Materi.findByPk(id, {
include: {
model: File
}
});
await Materi.destroy({
where: { id }
});
await Promise.all(materi.File.map((file) => new Promise((resolve, reject) => {
deleteFile(file.path).then(resolve).catch(reject);
})));
res.status(200).json({message: 'success'});
},
/**
Expand Down
6 changes: 5 additions & 1 deletion app/controllers/tugasController.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const { Tugas, SubmisiTugas, User } = require('../database/models');
const { ROLES } = require('../helper/constants');
const { parseForm } = require('../helper/parseform');
const { uploadFile } = require('../helper/uploader');
const { uploadFile, deleteFile } = require('../helper/uploader');

module.exports = {
/**
Expand Down Expand Up @@ -150,9 +150,13 @@ module.exports = {
async hapusSubmisi(req, res){
const id = req.params.id;
try{
const submisi = SubmisiTugas.findOne({
where: { id, pemilik: req.userToken.id }
});
await SubmisiTugas.destroy({
where: { id, pemilik: req.userToken.id }
});
await deleteFile(submisi.path);
res.json({message: 'success removing submisi'});
}
catch(err){
Expand Down
8 changes: 7 additions & 1 deletion app/helper/uploader.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,10 @@ async function uploadFile(localFile, destination) {
console.log(`${localFile} uploaded to ${bucketName}`);
}

module.exports = { uploadFile };
async function deleteFile(fileName){
await storage.bucket(bucketName).file(fileName).delete();

console.log(`gs://${bucketName}/${fileName} deleted`);
}

module.exports = { uploadFile, deleteFile };

0 comments on commit 32cebc2

Please sign in to comment.