I'm working on a Node.JS backend and I basically need to do these basic things:
- Save multiple files to Google Cloud Storage
- Save the array of GCS public urls to MongoDB
- Save "post" datas to Mongo DB along with the array of public urls
This is my code. At the end it works ans save all the things in Mongo DB but it seems messy. How can I fix these line of codes?
model/Post.js:
const mongoose = require('mongoose');
const {Schema} = mongoose;
const postSchema = new Schema({
title: {type: String},
subtitle: {type: String},
description: {type: String},
imagesUrl: [{type: String}],
_user: {
type: Schema.Types.ObjectId,
ref: 'User',
},
});
const Post = mongoose.model('Post', postSchema, 'posts');
module.exports = {
Post,
};
controllers/postController.js
const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const bucket = storage.bucket(process.env.GCLOUD_STORAGE_BUCKET);
//Func to save data into Mongo DB
const createPost = async (data) => {
try {
const post = await new Post({
title: data.title,
subtitle: data.subtitle,
description: data.description,
_user: data.userId,
});
await _.map(data.imagesUrl, (value, key) => {
post.imagesUrl.push(value);
});
post.save();
const userById = await User.findOne({_id: data.userId});
userById._posts.push(post);
await userById.save();
return post;
} catch (e) {
return e.stack;
}
};
//Func to upload files to GCS
const uploadFileTGcs = async (file) => {
let promises = [];
_.forEach(file, (value, key) => {
const {originalname, buffer} = value;
const blob = bucket.file(originalname.replace(/ /g, '_'));
const promise = new Promise((resolve, reject) => {
const blobStream = blob.createWriteStream({
resumable: false,
public: true,
});
blobStream.on('error', () => {
reject(`Unable to upload image, something went wrong`);
}).on('finish', async () => {
const publicUrl = format(
`https://storage.googleapis.com/${bucket.name}/${blob.name}`,
);
resolve(publicUrl);
}).end(buffer);
});
promises.push(promise);
});
const urls = Promise.all(promises).then(promises => {
return promises;
});
return urls;
};
routes/postRoute.js
router.post('/create', async (req, res, next) => {
try {
if (!req.files) {
res.status(400).json({
messages: 'No file uploaded',
});
return;
}
const imagesUrl = await postsController.uploadFileTGcs(req.files);
const postCreated = await postsController.createPost({
title: req.body.title,
subtitle: req.body.subtitle,
description: req.body.description,
imagesUrl: imagesUrl,
userId: req.user._id,
});
res.status(postCreated ? 200 : 404).json({
result: postCreated,
message: 'Post created',
});
} catch (e) {
res.status(500).json({
result: e.toString(),
});
}
});