Created
June 11, 2020 00:03
-
-
Save malnakli/8f353bc0765f2bf5fcef11f27e01158d 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
"use strict"; | |
/** | |
* Module dependencies | |
*/ | |
const admin = require("firebase-admin"); | |
module.exports = { | |
init(config) { | |
admin.initializeApp({ | |
credential: admin.credential.cert(config.serviceAccount), | |
storageBucket: config.bucket, | |
}); | |
const bucket = admin.storage().bucket(); | |
return { | |
upload(file) { | |
return new Promise((resolve, reject) => { | |
const path = file.path ? `${file.path}/` : ""; | |
const filename = `${path}${file.hash}${file.ext}`; | |
const buff = Buffer.from(file.buffer, "binary"); | |
const remoteFile = bucket.file(filename); | |
remoteFile.save( | |
buff, | |
{ | |
resumable: false, | |
contentType: file.mime, | |
public: true, | |
}, | |
(err) => { | |
if (err) { | |
reject(err); | |
} | |
file.url = `https://storage.googleapis.com/${config.bucket}/${filename}`; | |
resolve(); | |
} | |
); | |
}); | |
}, | |
delete(file) { | |
return new Promise((resolve, reject) => { | |
const path = file.path ? `${file.path}/` : ""; | |
const filename = `${path}${file.hash}${file.ext}`; | |
const remoteFile = bucket.file(filename); | |
remoteFile.delete((err, _) => { | |
if (err) { | |
return reject(err); | |
} | |
resolve(); | |
}); | |
}); | |
}, | |
}; | |
}, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment