first commit

This commit is contained in:
solehudin5699
2022-02-27 22:27:22 +07:00
commit 7761501545
7 changed files with 452 additions and 0 deletions
+14
View File
@@ -0,0 +1,14 @@
const logger = (req, res, next) => {
const time = new Date().toUTCString();
console.log(
`---------------------------------------------------------------\n${time}`,
JSON.stringify({
method: req.method,
path: req.path,
...req.headers,
})
);
next();
};
module.exports = logger;
+45
View File
@@ -0,0 +1,45 @@
const multer = require('multer');
const path = require('path');
//Disk for save file
const storage = multer.diskStorage({
destination: (req, res, cb) => {
cb(null, './public');
},
filename: (req, file, cb) => {
const nameFormat = `${Date.now()}-${file.fieldname}${path.extname(
file.originalname
)}`;
cb(null, nameFormat);
},
});
//Limit filesize
const limits = {
fileSize: 10_1000_1000,
};
const upload = multer({
storage,
limits,
});
const uploadMiddleware = (req, res, next) => {
const singleUpload = upload.single('image');
singleUpload(req, res, (err) => {
if (err) {
res.json({
success: false,
error: err,
});
} else if (!req.file) {
res.json({
success: false,
error: 'File not found',
});
} else {
next();
}
});
};
module.exports = uploadMiddleware;
+65
View File
@@ -0,0 +1,65 @@
const sharp = require('sharp');
const fs = require('fs');
const resizer = async (req, res) => {
try {
const { width, height, quality, format } = req.query;
const { filename } = req.params;
if (width) {
if (parseInt(width) > 5000) {
return res.status(400).json({
success: false,
message: 'Error. Width must be <=5000',
});
}
}
if (height) {
if (parseInt(height) > 5000) {
return res.status(400).json({
success: false,
message: 'Error. Height must be <=5000',
});
}
}
if (quality) {
if (parseInt(quality) > 100) {
return res.status(400).json({
success: false,
message: 'Error. Quality must be <=100',
});
}
}
const image = sharp(`./public/${filename}`);
let formatImage = (await image.metadata()).format;
formatImage = format || formatImage === 'svg' ? 'png' : formatImage;
const widthImage = width ? parseInt(width) : (await image.metadata()).width;
const heightImage = height
? parseInt(height)
: (await image.metadata()).height;
const resizedImage = await image
.resize(widthImage, heightImage)
.toFormat(formatImage, {
quality: quality ? parseInt(quality) : 100,
})
.withMetadata()
.toBuffer();
res.setHeader('content-type', 'image');
res.send(resizedImage);
fs.unlinkSync('public/' + filename);
} catch (error) {
res.setHeader('content-type', 'application/json');
res.status(500).json({
success: false,
message: 'Internal server error',
});
}
};
module.exports = resizer;