Skip to content

Instantly share code, notes, and snippets.

@johnkingzy
Created January 10, 2022 13:30
Show Gist options
  • Save johnkingzy/1e5ad1e07a1ab6e9cc1d03bde6b4f57a to your computer and use it in GitHub Desktop.
Save johnkingzy/1e5ad1e07a1ab6e9cc1d03bde6b4f57a to your computer and use it in GitHub Desktop.
import multer from 'multer';
import firebaseAdmin from 'firebase-admin';
import { default as serviceAccount } from '../../config/newapp-6a21b-firebase-adminsdk-l4qfa-aea1ab47b1.json';
export const config = {
api: {
bodyParser: false,
},
}
// Helper method to wait for a middleware to execute before continuing
// And to throw an error when an error happens in a middleware
function runMiddleware(req, res, fn) {
return new Promise((resolve, reject) => {
fn(req, res, (result) => {
if (result instanceof Error) {
return reject(result)
}
return resolve(result)
})
})
}
const uploader = multer({
storage: multer.memoryStorage(),
limits: {
fileSize: 5 * 1024 * 1024, // keep images size < 5 MB
},
}).single('resumeFile');
if (!firebaseAdmin.apps.length) {
firebaseAdmin.initializeApp({
credential: firebaseAdmin.credential.cert(serviceAccount),
databaseURL: 'https://newapp-6a21b.firebaseio.com',
});
}
const storage = firebaseAdmin.storage();
async function handler(req, res) {
await runMiddleware(req, res, uploader);
if (!req.file) {
res.status(400).send('No file uploaded.');
return;
}
try {
const bucket = storage.bucket('gs://newapp-6a21b.appspot.com')
// Create new blob in the bucket referencing the file
const blob = bucket.file(`resume/${req.file.originalname}`);
// Create writable stream and specifying file mimetype
const blobWriter = blob.createWriteStream({
metadata: {
contentType: req.file.mimetype,
},
});
blobWriter.on('error', console.error);
blobWriter.on('finish', () => {
// Assembling public URL for accessing the file via HTTP
const publicUrl = `https://firebasestorage.googleapis.com/v0/b/${
bucket.name
}/o/${encodeURIComponent(blob.name)}?alt=media`;
// Return the file name and its public URL
res
.status(200)
.send({ fileName: req.file.originalname, fileLocation: publicUrl });
});
// When there is no more data to be consumed from the stream
blobWriter.end(req.file.buffer);
} catch (error) {
console.log('error :>> ', error);
res.status(500).json({
message: 'An error occured, please try again',
});
}
}
export default handler;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment