-
Notifications
You must be signed in to change notification settings - Fork 38
/
index.js
98 lines (75 loc) · 2.56 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
// 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';
const { Storage } = require('@google-cloud/storage');
const BaseStore = require('ghost-storage-base');
const path = require('path');
let options = {};
class GStore extends BaseStore {
constructor(config = {}){
super(config);
options = config;
const gcs = new Storage({
keyFilename: options.key
});
this.bucket = gcs.bucket(options.bucket);
this.assetDomain = options.assetDomain || `${options.bucket}.storage.googleapis.com`;
if(options.hasOwnProperty('assetDomain')){
this.insecure = options.insecure;
}
this.maxAge = options.maxAge || 2678400;
}
async save(image) {
if (!options) {
throw new Error('Google Cloud Storage is not configured.')
}
const targetDir = this.getTargetDir();
const googleStoragePath = `http${this.insecure?'':'s'}://${this.assetDomain}/`;
let targetFilename;
const newFile = await this.getUniqueFileName(image, targetDir);
targetFilename = newFile;
const opts = {
destination: newFile,
metadata: {
cacheControl: `public, max-age=${this.maxAge}`
},
public: true
};
await this.bucket.upload(image.path, opts);
return googleStoragePath + targetFilename;
}
// middleware for serving the files
serve() {
// a no-op, these are absolute URLs
return function (req, res, next) { next(); };
}
async exists (filename, targetDir) {
const data = await this.bucket.file(path.join(targetDir, filename)).exists();
return data[0];
}
read (filename) {
const rs = this.bucket.file(filename).createReadStream();
let contents = null;
return new Promise((resolve, reject) => {
rs.on('error', err => {
return reject(err);
});
rs.on('data', data => {
if (!contents) {
contents = data;
} else {
contents = Buffer.concat([contents, data]);
}
});
rs.on('end', () => {
return resolve(contents);
});
});
}
delete (filename) {
return this.bucket.file(filename).delete();
}
}
module.exports = GStore;