Skip to content

Commit

Permalink
Merge pull request #154 from dali-lab/add-blog-endpoint
Browse files Browse the repository at this point in the history
feat: store uploaded files in firebase
  • Loading branch information
wu-ciesielska authored Dec 13, 2023
2 parents 3df7fb4 + ddbd8df commit c00a842
Show file tree
Hide file tree
Showing 7 changed files with 866 additions and 29 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"express": "^4.16.3",
"firebase-admin": "^12.0.0",
"jwt-simple": "^0.5.6",
"mongoose": "^6.10.4",
"morgan": "^1.9.0",
Expand Down
21 changes: 14 additions & 7 deletions src/controllers/blog.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import mongoose from 'mongoose';
import { RESPONSE_CODES } from '../constants';
import { Blog } from '../models';
import { getFilePath } from '../utils/upload-file';
import { uploadFileToFirebase } from '../utils';

/**
* @description retrieves blog post object
Expand Down Expand Up @@ -61,14 +61,17 @@ export const createBlogPost = async (fields, uploadedFile, user) => {

const { first_name: firstName, last_name: lastName, _id: id } = user;

const imagePath = getFilePath(uploadedFile?.path);

post.title = title;
post.body = body;
post.author = `${firstName} ${lastName}`;
post.authorId = id;
post.image = imagePath;

if (uploadedFile) {
const filePath = await uploadFileToFirebase(
uploadedFile.path,
`uploads/${uploadedFile.filename}`,
);
post.image = filePath;
}
try {
const savedPost = await post.save();
return savedPost.toJSON();
Expand Down Expand Up @@ -112,8 +115,12 @@ export const updateBlogPost = async (id, fields, uploadedFile) => {
const postId = new mongoose.Types.ObjectId(id);

if (uploadedFile) {
const imagePath = getFilePath(uploadedFile?.path);
await Blog.updateOne({ _id: postId }, { ...fields, image: imagePath });
const filePath = await uploadFileToFirebase(
uploadedFile.path,
`uploads/${uploadedFile.filename}`,
);

await Blog.updateOne({ _id: postId }, { ...fields, image: filePath });
} else {
await Blog.updateOne({ _id: postId }, fields);
}
Expand Down
3 changes: 1 addition & 2 deletions src/routers/blog.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,9 @@ import {
RESPONSE_TYPES,
generateResponse,
} from '../constants';
import { queryFetch } from '../utils';
import { queryFetch, uploadFile } from '../utils';
import { Blog, User } from '../controllers';
import { requireAuth } from '../middleware';
import { uploadFile } from '../utils/upload-file';

const blogRouter = Router();

Expand Down
14 changes: 14 additions & 0 deletions src/utils/firebase-admin.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import dotenv from 'dotenv';
import admin from 'firebase-admin';

// initialize dotenv here in case env variable was not yet available
if (!process.env.FIREBASE_API_KEY) {
dotenv.config({ silent: true });
}

admin.initializeApp({
credential: admin.credential.cert(JSON.parse(process.env.FIREBASE_API_KEY)),
storageBucket: 'gs://pine-beetle-prediction.appspot.com',
});

export default admin;
7 changes: 7 additions & 0 deletions src/utils/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,11 @@ import {
generateLocationListPipeline,
} from './aggregate';

import {
uploadFileToFirebase,
uploadFile,
} from './upload-file';

export {
aggregate,
generateLocationPipeline,
Expand All @@ -30,4 +35,6 @@ export {
queryFetch,
sendPasswordResetEmail,
specifiedQueryFetch,
uploadFile,
uploadFileToFirebase,
};
27 changes: 19 additions & 8 deletions src/utils/upload-file.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,27 @@
import * as path from 'path';
import multer from 'multer';
import admin from './firebase-admin';

const uploadFilePath = path.resolve(__dirname, '../..', 'public/uploads');
const bucket = admin.storage().bucket();

const uploadFileToFirebase = async (filePath, destination) => {
await bucket.upload(filePath, {
destination,
});

// Get public URL for the file
const file = bucket.file(destination);
const signedUrls = await file.getSignedUrl({
action: 'read',
expires: '03-09-2491',
});

const getFilePath = (originalPath) => {
if (originalPath) {
const newPath = originalPath.split('/public')[1];
return newPath || originalPath;
}
return null;
const publicUrl = signedUrls[0];
return publicUrl;
};

const uploadFilePath = path.resolve(__dirname, '../..', 'public/uploads');

const storageFile = multer.diskStorage({
destination: uploadFilePath,
filename: (_req, file, fn) => {
Expand Down Expand Up @@ -52,4 +63,4 @@ const uploadFile = multer({
},
}).single('image');

export { uploadFile, getFilePath };
export { uploadFile, uploadFileToFirebase };
Loading

0 comments on commit c00a842

Please sign in to comment.