Skip to content

Commit 508be38

Browse files
author
Satyajit Dey
committed
BE #6 Save image info after s3 upload
1 parent 9181126 commit 508be38

File tree

2 files changed

+41
-4
lines changed

2 files changed

+41
-4
lines changed

controllers/binaries.controller.js

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ const AWS = require('aws-sdk');
33
const mime = require('mime-types');
44
const {v4: uuidv4} = require('uuid');
55

6+
const ImageModel = require('../models/images.model');
7+
68
AWS.config.update({
79
accessKeyId: process.env.IAM_ACCESS_KEY,
810
secretAccessKey: process.env.IAM_SECRET_KEY,
@@ -14,7 +16,8 @@ const s3 = new AWS.S3();
1416
exports.uploadImage = (req, res) => {
1517
let fileInfo = {
1618
source: req.file.path,
17-
key: `${uuidv4()}---${req.file.filename}`,
19+
key: `${uuidv4()}---${req.file.filename}`,
20+
caption: req.body.caption,
1821
contentType: mime.lookup(req.file.path),
1922
author: req.jwt.name,
2023
authorEmail: req.jwt.email
@@ -46,11 +49,24 @@ let uploadFile = (fileInfo, res) => {
4649
}
4750
};
4851

52+
//Upload image to S3 bucket
4953
s3.upload(params, (err, data) => {
5054
if (err) {
5155
return res.status(500).send({error: err});
5256
}
5357

58+
let keys = fileInfo.key.split('---');
59+
const imageData = {
60+
_id: keys[0],
61+
fileName: keys[1],
62+
caption: fileInfo.caption,
63+
author: fileInfo.author
64+
};
65+
66+
//After successful upload save the image info to Image Mongo model
67+
ImageModel.saveImage(imageData);
68+
69+
//After successful upload delete the local image
5470
fs.unlink(fileInfo.source, (err) => {
5571
if (err) throw err;
5672
console.log(`${fileInfo.source} deleted.`)

models/images.model.js

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,30 @@
11
const mongoose = require('../services/db.service').mongoose;
22

33
const imageSchema = new mongoose.Schema({
4-
imageId: {type: String, required: true, trim: true},
4+
_id: {type: String},
55
fileName: {type: String, required: true, trim: true},
6-
storage: {type: String, required: true, trim: true},
76
caption: {type: String},
7+
author: {type: String, trim: true},
8+
credits: [String],
9+
imageType: {type: String},
10+
copyright: {type: String, trim: true},
811
createdAt: {type: Date, default: Date.now},
9-
});
12+
status: {type: String, default: 'published'}
13+
});
14+
15+
const Images = mongoose.model('Image', imageSchema);
16+
17+
exports.saveImage = (imageData) => {
18+
const image = new Images(imageData);
19+
return image.save();
20+
};
21+
22+
exports.findById = (id) => {
23+
Images.findById(id).then(result => {
24+
return result;
25+
});
26+
};
27+
28+
exports.findByAuthor = (email) => {
29+
return Images.find({author: email});
30+
};

0 commit comments

Comments
 (0)