-
Notifications
You must be signed in to change notification settings - Fork 19
/
index.js
96 lines (90 loc) · 2.86 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
const Minio = require('minio');
const mime = require("mime-types");
module.exports = {
init(providerOptions) {
const { port, useSSL, endPoint, accessKey, secretKey, bucket, folder, private = false, expiry = 7 * 24 * 60 * 60 } = providerOptions;
const isUseSSL = (useSSL === 'true' || useSSL === true);
const MINIO = new Minio.Client({
endPoint,
port: +port || 9000,
useSSL: isUseSSL,
accessKey,
secretKey,
});
const getUploadPath = (file) => {
const pathChunk = file.path ? `${file.path}/` : '';
const path = folder ? `${folder}/${pathChunk}` : pathChunk;
return `${path}${file.hash}${file.ext}`;
};
const getHostPart = () => {
const protocol = isUseSSL ? 'https://' : 'http://';
const portSuffix = ((isUseSSL && +port === 443) || (isUseSSL && +port === 80)) ? '' : `:${port}`;
return protocol + endPoint + portSuffix + '/';
};
const getFilePath = (file) => {
const hostPart = getHostPart() + bucket + '/';
const path = file.url.replace(hostPart, '');
return path;
};
return {
uploadStream(file) {
return this.upload(file);
},
upload(file) {
return new Promise((resolve, reject) => {
const path = getUploadPath(file);
const metaData = {
'Content-Type': mime.lookup(file.ext) || 'application/octet-stream',
}
MINIO.putObject(
bucket,
path,
file.stream || Buffer.from(file.buffer, 'binary'),
metaData,
(err, _etag) => {
if (err) {
return reject(err);
}
const hostPart = getHostPart();
const filePath = `${bucket}/${path}`;
file.url = `${hostPart}${filePath}`;
resolve();
}
);
});
},
delete(file) {
return new Promise((resolve, reject) => {
const path = getFilePath(file);
MINIO.removeObject(bucket, path, err => {
if (err) {
return reject(err);
}
resolve();
});
});
},
isPrivate: () => {
return (private === 'true' || private === true);
},
getSignedUrl(file) {
return new Promise((resolve, reject) => {
const url = new URL(file.url);
if (url.hostname !== endPoint) {
resolve({ url: file.url });
} else if (!url.pathname.startsWith(`/${bucket}/`)) {
resolve({ url: file.url });
} else {
const path = getFilePath(file);
MINIO.presignedGetObject(bucket, path, +expiry, (err, presignedUrl) => {
if (err) {
return reject(err);
}
resolve({ url: presignedUrl });
});
}
});
},
};
},
};