2018-01-06 12:54:02 +08:00
|
|
|
"use strict";
|
|
|
|
|
2018-11-05 19:52:50 +08:00
|
|
|
const imageService = require('../../services/image');
|
2018-04-01 23:42:12 +08:00
|
|
|
const repository = require('../../services/repository');
|
2018-01-08 03:07:59 +08:00
|
|
|
const RESOURCE_DIR = require('../../services/resource_dir').RESOURCE_DIR;
|
|
|
|
const fs = require('fs');
|
2018-01-06 12:54:02 +08:00
|
|
|
|
2018-03-31 05:07:41 +08:00
|
|
|
async function returnImage(req, res) {
|
2018-04-01 23:42:12 +08:00
|
|
|
const image = await repository.getImage(req.params.imageId);
|
2018-01-06 12:54:02 +08:00
|
|
|
|
|
|
|
if (!image) {
|
2018-03-31 07:31:22 +08:00
|
|
|
return res.sendStatus(404);
|
2018-01-06 12:54:02 +08:00
|
|
|
}
|
2018-01-08 03:07:59 +08:00
|
|
|
else if (image.data === null) {
|
|
|
|
res.set('Content-Type', 'image/png');
|
|
|
|
return res.send(fs.readFileSync(RESOURCE_DIR + '/db/image-deleted.png'));
|
|
|
|
}
|
2018-01-06 12:54:02 +08:00
|
|
|
|
|
|
|
res.set('Content-Type', 'image/' + image.format);
|
|
|
|
|
|
|
|
res.send(image.data);
|
2018-03-31 05:07:41 +08:00
|
|
|
}
|
2018-01-06 12:54:02 +08:00
|
|
|
|
2018-03-31 07:31:22 +08:00
|
|
|
async function uploadImage(req) {
|
2018-01-07 10:49:02 +08:00
|
|
|
const noteId = req.query.noteId;
|
2018-01-06 12:54:02 +08:00
|
|
|
const file = req.file;
|
|
|
|
|
2018-04-01 23:42:12 +08:00
|
|
|
const note = await repository.getNote(noteId);
|
2018-01-07 10:49:02 +08:00
|
|
|
|
|
|
|
if (!note) {
|
2018-03-31 07:31:22 +08:00
|
|
|
return [404, `Note ${noteId} doesn't exist.`];
|
2018-01-07 10:49:02 +08:00
|
|
|
}
|
2018-01-06 12:54:02 +08:00
|
|
|
|
2018-01-07 22:22:55 +08:00
|
|
|
if (!["image/png", "image/jpeg", "image/gif"].includes(file.mimetype)) {
|
2018-03-31 07:31:22 +08:00
|
|
|
return [400, "Unknown image type: " + file.mimetype];
|
2018-01-06 12:54:02 +08:00
|
|
|
}
|
|
|
|
|
2018-11-05 19:52:50 +08:00
|
|
|
const {url} = await imageService.saveImage(file.buffer, file.originalname, noteId);
|
2018-01-06 12:54:02 +08:00
|
|
|
|
2018-03-31 07:31:22 +08:00
|
|
|
return {
|
2018-01-06 12:54:02 +08:00
|
|
|
uploaded: true,
|
2018-11-05 19:52:50 +08:00
|
|
|
url
|
2018-03-31 07:31:22 +08:00
|
|
|
};
|
2018-03-31 05:07:41 +08:00
|
|
|
}
|
2018-01-06 12:54:02 +08:00
|
|
|
|
2018-03-31 05:07:41 +08:00
|
|
|
module.exports = {
|
|
|
|
returnImage,
|
|
|
|
uploadImage
|
|
|
|
};
|