From 32cebc29442d226821e9f46fdcf6d38836f63d5a Mon Sep 17 00:00:00 2001 From: Fransiskus Febryan Suryawan Date: Sat, 3 Jul 2021 13:40:09 +0700 Subject: [PATCH] Add file deletion from bucket --- app/controllers/materiController.js | 10 +++++++++- app/controllers/tugasController.js | 6 +++++- app/helper/uploader.js | 8 +++++++- 3 files changed, 21 insertions(+), 3 deletions(-) diff --git a/app/controllers/materiController.js b/app/controllers/materiController.js index dd89f08..4e113df 100644 --- a/app/controllers/materiController.js +++ b/app/controllers/materiController.js @@ -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 = { @@ -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'}); }, /** diff --git a/app/controllers/tugasController.js b/app/controllers/tugasController.js index a94cc7e..abb6a00 100644 --- a/app/controllers/tugasController.js +++ b/app/controllers/tugasController.js @@ -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 = { /** @@ -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){ diff --git a/app/helper/uploader.js b/app/helper/uploader.js index a79efb7..d523d31 100644 --- a/app/helper/uploader.js +++ b/app/helper/uploader.js @@ -22,4 +22,10 @@ async function uploadFile(localFile, destination) { console.log(`${localFile} uploaded to ${bucketName}`); } -module.exports = { uploadFile }; \ No newline at end of file +async function deleteFile(fileName){ + await storage.bucket(bucketName).file(fileName).delete(); + + console.log(`gs://${bucketName}/${fileName} deleted`); +} + +module.exports = { uploadFile, deleteFile }; \ No newline at end of file