-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
98 lines (91 loc) · 2.42 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
98
const BaseAdapter = require('./BaseStorage')
const COS = require('cos-nodejs-sdk-v5')
const assert = require('assert')
const fs = require('fs')
const path = require('path')
const debug = require('debug')('tencentyun-storage')
const util = require('util')
class TencentyunCOSAdapter extends BaseAdapter {
constructor ({
SecretId,
SecretKey,
baseDir = '/',
Bucket,
Region
}) {
super()
assert(SecretId)
assert(SecretKey)
assert(Bucket)
assert(Region)
this.cosParam = { Bucket, Region }
this.cos = new COS({ SecretId, SecretKey })
this.baseDir = baseDir
}
async exists (fileName, targetDir) {
debug('exists', 'filename', fileName, 'targetDir', targetDir)
const params = {
...this.cosParam,
Key: path.join(targetDir, fileName).replace(/\\/g, '/')
}
debug('exists params is', params)
try {
await util.promisify(this.cos.headObject).call(this.cos, params)
return true
} catch (error) {
debug('exists error', error)
return false
}
}
async save (image, targetDir) {
debug('save image is', image, 'targetDir is', targetDir)
targetDir = targetDir || this.getTargetDir(this.baseDir)
const uniqueFileName = await this.getUniqueFileName(image, targetDir)
debug('save getUniqueFileName result is ', uniqueFileName)
const params = {
...this.cosParam,
Key: uniqueFileName,
ContentLength: image.size,
ContentType: image.type,
Body: fs.createReadStream(image.path)
}
const res = await util.promisify(this.cos.putObject).call(this.cos, params)
debug('save', res)
// todo: change to STATIC_IMAGE_URL_PREFIX
return '/content/images' + uniqueFileName
}
/**
* unnecessary to implement.
* @returns {Function}
*/
serve () {
return (req, res, next) => {
this.cos.getObject({
...this.cosParam,
Key: path.join(this.baseDir, req.path).replace(/\\/g, '/'),
Output: res
}, function (err) {
if (err) {
debug('serve error', err)
res.status(404)
next()
}
})
}
}
/**
* Not implemented.
* @returns {Promise.<*>}
*/
delete () {
return Promise.reject(new Error('not implemented'))
}
/**
* Not implemented.
* @returns {Promise.<*>}
*/
read () {
return Promise.reject(new Error('not implemented'))
}
}
module.exports = TencentyunCOSAdapter