forked from mitchellst/ghost-google-cloud-storage
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
92 lines (80 loc) · 2.79 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
// this package had a bug that made it unusable.
// forked it and fixed and submitted a PR
//module.exports = require('ghost-google-cloud-storage');
// but for now...
'use strict';
var storage = require('@google-cloud/storage'),
BaseStore = require('ghost-storage-base'),
Promise = require('bluebird'),
options = {};
class GStore extends BaseStore {
constructor(config = {}){
super(config);
options = config;
var gcs = storage({
projectId: options.projectId,
keyFilename: options.key
});
this.bucket = gcs.bucket(options.bucket);
this.assetDomain = options.assetDomain || `${options.bucket}.storage.googleapis.com`;
// only set insecure from config if assetDomain is set
if(options.hasOwnProperty('assetDomain')){
this.insecure = options.insecure;
}
// default max-age is 3600 for GCS, override to something more useful
this.maxAge = options.maxAge || 2678400;
}
save(image) {
if (!options) return Promise.reject('google cloud storage is not configured');
var targetDir = this.getTargetDir(),
googleStoragePath = `http${this.insecure?'':'s'}://${this.assetDomain}/`,
targetFilename;
return new Promise((resolve, reject) => {
this.getUniqueFileName(image, targetDir).then(tf => {
targetFilename = tf;
var opts = {
destination: targetFilename,
metadata: {
cacheControl: `public, max-age=${this.maxAge}`
},
public: true
};
return this.bucket.upload(image.path, opts);
}).then(function (data) {
return resolve(googleStoragePath + targetFilename);
}).catch(function (e) {
return reject(e);
});
});
}
// middleware for serving the files
serve() {
// a no-op, these are absolute URLs
return function (req, res, next) { next(); };
}
exists (filename) {
return new Promise((resolve, reject) => {
this.bucket.file(filename).exists().then(function(data){
return resolve(data[0]);
});
});
}
read (filename) {
var rs = this.bucket.file(filename).createReadStream(), contents = '';
return new Promise(function (resolve, reject) {
rs.on('error', function(err){
return reject(err);
});
rs.on('data', function(data){
contents += data;
});
rs.on('end', function(){
return resolve(content);
});
});
}
delete (filename) {
return this.bucket.file(filename).delete();
}
}
module.exports = GStore;