-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
97 lines (83 loc) · 2.5 KB
/
index.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
const StorageBase = require('ghost-storage-base');
const fs = require('fs');
const S3 = require('aws-sdk/clients/s3');
class Storage extends StorageBase {
constructor(config = {}) {
super(config);
const {
bucket,
endpoint,
accessKeyId,
secretAccessKey,
publicDomain
} = config;
this.bucket = bucket;
this.endpoint = endpoint;
this.accessKeyId = accessKeyId;
this.secretAccessKey = secretAccessKey;
this.signatureVersion = 'v4';
this.domain = publicDomain;
this.s3 = new S3({
endpoint: this.endpoint,
accessKeyId: this.accessKeyId,
secretAccessKey: this.secretAccessKey,
signatureVersion: this.signatureVersion,
});
};
exists(filename) {
return s3.headObject({
Bucket: this.bucket,
Key: filename
}).promise()
.then(() => true)
.catch(() => false);
}
async save(image) {
const now = new Date();
const fileKey = `content/uploads/${now.getFullYear()}/${now.getMonth() + 1}/${now.getDate()}/${image.name}`;
return fs.promises.readFile(image.path)
.then(async (buffer) => {
const params = {
ACL: 'public-read',
Bucket: this.bucket,
Key: fileKey,
Body: buffer,
ContentType: image.type,
CacheControl: 'max-age=31536000'
};
await this.s3.putObject(params).promise();
return `${this.domain}/${fileKey}`;
});
}
serve() {
return (req, res, next) => {
const params = {
Bucket: this.bucket,
Key: req.path.replace(/^\//, '')
};
return this.s3.getObject(params)
.createReadStream()
.on('error', next())
.pipe(res);
};
};
async delete(fileName) {
try {
await this.s3.deleteObject({
Bucket: this.bucket,
Key: fileName
}).promise();
return true;
} catch {
return false;
}
}
async read(options) {
return this.s3.getObject({
Bucket: options.bucket,
Key: options.path
}).promise()
.then((data) => data.Body);
}
}
module.exports = Storage;