112 lines
2.6 KiB
JavaScript
112 lines
2.6 KiB
JavaScript
|
const AWS = require('aws-sdk')
|
||
|
const fs = require('fs')
|
||
|
const path = require('path')
|
||
|
const imagemin = require('imagemin')
|
||
|
const imageminJpegtran = require('imagemin-jpegtran')
|
||
|
const imageminPngquant = require('imagemin-pngquant')
|
||
|
|
||
|
class Aws {
|
||
|
constructor () {
|
||
|
AWS.config.update({
|
||
|
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
|
||
|
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY
|
||
|
})
|
||
|
}
|
||
|
|
||
|
_send (params, callback) {
|
||
|
fs.readFile(params.path, (err, data) => {
|
||
|
if (err) {
|
||
|
callback(err, null)
|
||
|
return false
|
||
|
}
|
||
|
const base64data = Buffer.from(data, 'binary')
|
||
|
const dest = path.join(process.env.AWS_BASEFOLDER, params.filename)
|
||
|
const s3 = new AWS.S3()
|
||
|
|
||
|
s3.putObject({
|
||
|
Bucket: process.env.AWS_BUCKET,
|
||
|
Key: dest,
|
||
|
Body: base64data,
|
||
|
ACL: 'public-read'
|
||
|
}, (err, res) => {
|
||
|
if (err) {
|
||
|
callback(err, res)
|
||
|
} else {
|
||
|
callback(null, {
|
||
|
file: process.env.AWS_URL + dest
|
||
|
})
|
||
|
}
|
||
|
})
|
||
|
})
|
||
|
}
|
||
|
|
||
|
_compress (params, callback) {
|
||
|
const newFile = params.path + '.' + params.filename.split('.')[1]
|
||
|
|
||
|
fs.copyFile(params.path, newFile, (err, res) => {
|
||
|
if (err) {
|
||
|
callback(err, null)
|
||
|
return false
|
||
|
}
|
||
|
|
||
|
(async () => {
|
||
|
const file = await imagemin([newFile], '/tmp', {
|
||
|
plugins: [
|
||
|
imageminJpegtran(),
|
||
|
imageminPngquant({ quality: '65-80' })
|
||
|
]
|
||
|
})
|
||
|
|
||
|
this._send({
|
||
|
path: file[0].path,
|
||
|
filename: params.filename
|
||
|
}, (err, res) => {
|
||
|
callback(err, res)
|
||
|
fs.unlink(file[0].path, () => {})
|
||
|
})
|
||
|
})()
|
||
|
})
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Upload file on s3
|
||
|
* @param {Object} params {path: String, filename: String}
|
||
|
* @param {Function} callback
|
||
|
*/
|
||
|
upload (params, callback) {
|
||
|
fs.readFile(params.path, (err, data) => {
|
||
|
if (err) {
|
||
|
callback(err, null)
|
||
|
return false
|
||
|
}
|
||
|
|
||
|
this._compress(params, callback)
|
||
|
})
|
||
|
}
|
||
|
|
||
|
deleteObjects (files, callback) {
|
||
|
const s3 = new AWS.S3()
|
||
|
const basePath = process.env.AWS_URL + process.env.AWS_BASEFOLDER
|
||
|
let items = []
|
||
|
|
||
|
files.forEach((file) => {
|
||
|
if (file) {
|
||
|
items.push({ Key: file.replace(basePath, '') })
|
||
|
}
|
||
|
})
|
||
|
|
||
|
if (items.length > 0) {
|
||
|
s3.deleteObjects({
|
||
|
Bucket: process.env.AWS_BUCKET,
|
||
|
Delete: { // required
|
||
|
Objects: items
|
||
|
}
|
||
|
}, callback)
|
||
|
} else {
|
||
|
callback(null, { code: 200, res: 'No file deleted' })
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
module.exports = Aws
|