1
0
Fork 0
mirror of https://github.com/seejohnrun/haste-server.git synced 2024-11-25 05:51:22 +00:00
haste-server/lib/document_stores/google-datastore.js

90 lines
2.3 KiB
JavaScript
Raw Normal View History

2018-08-27 21:59:05 +00:00
/*global require,module,process*/
2018-08-27 22:15:02 +00:00
const Datastore = require('@google-cloud/datastore');
2018-08-27 21:59:05 +00:00
const winston = require('winston');
class GoogleDatastoreDocumentStore {
// Create a new store with options
constructor(options) {
this.kind = "Haste";
this.expire = options.expire;
this.datastore = new Datastore();
}
// Save file in a key
set(key, data, callback, skipExpire) {
var expireTime = (skipExpire || this.expire === undefined) ? null : new Date(Date.now() + this.expire * 1000);
2018-08-27 21:59:05 +00:00
var taskKey = this.datastore.key([this.kind, key])
var task = {
key: taskKey,
data: [
{
name: 'value',
value: data,
excludeFromIndexes: true
},
{
name: 'expiration',
value: expireTime
}
]
};
2018-08-27 21:59:05 +00:00
this.datastore.insert(task).then(() => {
callback(true);
2018-08-27 21:59:05 +00:00
})
.catch(err => {
callback(false);
});
}
// Get a file from a key
get(key, callback, skipExpire) {
var taskKey = this.datastore.key([this.kind, key])
2018-08-27 21:59:05 +00:00
this.datastore.get(taskKey).then((entity) => {
2018-08-28 00:21:37 +00:00
if (skipExpire || entity[0]["expiration"] == null) {
2018-08-27 21:59:05 +00:00
callback(entity[0]["value"]);
}
else {
// check for expiry
2018-08-28 00:21:37 +00:00
if (entity[0]["expiration"] < new Date()) {
winston.info("document expired", {key: key, expiration: entity[0]["expiration"], check: new Date(null)});
2018-08-27 21:59:05 +00:00
callback(false);
}
else {
// update expiry
var task = {
key: taskKey,
data: [
{
name: 'value',
value: entity[0]["value"],
excludeFromIndexes: true
},
{
name: 'expiration',
value: new Date(Date.now() + this.expire * 1000)
2018-08-27 21:59:05 +00:00
}
]
};
this.datastore.update(task).then(() => {
})
.catch(err => {
winston.error("failed to update expiration", {error: err});
});
callback(entity[0]["value"]);
}
}
})
.catch(err => {
winston.error("Error retrieving value from Google Datastore", {error: err});
callback(false);
});
2018-08-27 22:15:02 +00:00
}
2018-08-27 21:59:05 +00:00
}
module.exports = GoogleDatastoreDocumentStore;