-
Notifications
You must be signed in to change notification settings - Fork 0
/
image-cache.js
70 lines (59 loc) · 1.66 KB
/
image-cache.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
'use strict';
const fs = require('fs');
const got = require('got');
const Storage = require('@google-cloud/storage');
const CryptoJS = require('crypto-js');
const Base62 = require("base62/lib/ascii");
function ImageCache(projectId, bucketId, salt) {
const storage = Storage({ projectId: projectId });
const bucket = storage.bucket(bucketId);
this.store = function(readStream, key, mimetype) {
return new Promise((resolve, reject) => {
const cacheId = getCacheId(key, salt);
const file = bucket.file(cacheId);
const writeStream = file.createWriteStream({
metadata: {
contentType: mimetype
},
resumable: false
});
writeStream.on('error', error => {
reject(error);
});
writeStream.on('finish', () => {
file.makePublic().then(() => {
resolve(getPublicUrl(bucketId, cacheId));
});
});
readStream.pipe(writeStream);
});
};
this.find = function(key) {
return new Promise((resolve, reject) => {
const cacheId = getCacheId(key, salt);
bucket.file(cacheId).exists()
.then(function(data) {
const exists = data[0];
if (exists) {
resolve(getPublicUrl(bucketId, cacheId));
} else {
resolve();
}
})
.catch(error => {
reject(error);
});
});
}
}
function getPublicUrl(bucketId, cacheId) {
return `https://storage.googleapis.com/${bucketId}/${cacheId}`;
}
function getCacheId(key, salt) {
return Base62.encode(
parseInt(
CryptoJS.SHA3(key + salt, {
outputLength: 224
}).toString(CryptoJS.enc.Hex), 16));
}
module.exports = ImageCache;