-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
82 lines (74 loc) · 2.41 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
const StorageBase = require('ghost-storage-base'),
{Storage} = require('@google-cloud/storage');
//const common = require('../../../../current/core/server/lib/common');
class GStore extends StorageBase {
constructor(config) {
super();
var storage = new Storage({"keyFilename": config.key});
this.bucket = storage.bucket(config.bucket)
}
exists(fileName, targetDir) {
return new Promise((resolve, reject) => {
this.bucket.file(targetDir+'/'+fileName).exists()
.then(data=>{
resolve(data[0])
})
})
}
/**
* Saves the image to google cloud storage
* - image is the express image object
* - returns a promise which ultimately returns the full url to the uploaded image
*
* @param image
* @param targetDir
* @returns {*}
*/
save(image, targetDir) {
return new Promise((resolve, reject) => {
targetDir = this.getTargetDir()
this.getUniqueFileName(image, targetDir).then(filename=>{
var opts = {
predefinedAcl: 'publicRead',
destination: filename
}
return this.bucket.upload(image.path, opts)
}).then(response =>{
var url = 'https://storage.googleapis.com/'+
response[0].metadata.bucket+'/'+
response[0].name
resolve(url)
}).catch(e=>{
//common.logging.error(JSON.stringify(e))
reject(e)
});
})
}
serve() {
return function(req, res, next) {
next();
};
}
delete(filename) {
//common.logging.info('delete:')
//common.logging.info(JSON.stringify(filename))
return this.bucket.file(filename).delete();
}
read(filename) {
//common.logging.info('read:')
//common.logging.info('file name: '+filename)
var rs = this.bucket.file(filename).createReadStream(), contents = '';
return new Promise(function (resolve, reject) {
rs.on('error', function(err){
reject(err);
});
rs.on('data', function(data){
contents += data;
});
rs.on('end', function(){
resolve(content);
});
});
}
}
module.exports = GStore;