-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy paths3.js
71 lines (62 loc) · 1.92 KB
/
s3.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
'use strict'
const fs = require('fs')
const path = require('path')
const config = require('../config')
const { getImageMimeType } = require('../utils')
const logger = require('../logger')
const { S3Client } = require('@aws-sdk/client-s3-node/S3Client')
const { PutObjectCommand } = require('@aws-sdk/client-s3-node/commands/PutObjectCommand')
const credentials = {
accessKeyId: config.s3.accessKeyId,
secretAccessKey: config.s3.secretAccessKey
}
const s3 = new S3Client({
credentials,
region: config.s3.region,
endpoint: config.s3.endpoint
})
exports.uploadImage = function (imagePath, callback) {
if (!imagePath || typeof imagePath !== 'string') {
callback(new Error('Image path is missing or wrong'), null)
return
}
if (!callback || typeof callback !== 'function') {
logger.error('Callback has to be a function')
return
}
fs.readFile(imagePath, function (err, buffer) {
if (err) {
callback(new Error(err), null)
return
}
const params = {
Bucket: config.s3bucket,
Key: path.join('uploads', path.basename(imagePath)),
Body: buffer,
ACL: 'public-read'
}
const mimeType = getImageMimeType(imagePath)
if (mimeType) { params.ContentType = mimeType }
const command = new PutObjectCommand(params)
s3.send(command).then(data => {
// default scheme settings to https
let s3Endpoint = 'https://s3.amazonaws.com'
if (config.s3.region && config.s3.region !== 'us-east-1') {
s3Endpoint = `s3-${config.s3.region}.amazonaws.com`
}
// rewrite endpoint from config
if (config.s3.endpoint) {
s3Endpoint = config.s3.endpoint
}
if (config.s3.baseURL) {
callback(null, `${config.s3.baseURL}/${params.Key}`)
} else {
callback(null, `${s3Endpoint}/${config.s3bucket}/${params.Key}`)
}
}).catch(err => {
if (err) {
callback(new Error(err), null)
}
})
})
}