andresusandi-storage
Version:
storage utilities for distributed systems
59 lines (48 loc) • 2.11 kB
JavaScript
const { Datastore } = require('@google-cloud/datastore');
const { name: packageName } = require('./package.json');
const { v4: uuid } = require('uuid');
class GoogleCloudStorage {
constructor(name, projectId, keyFilename) {
this.datastore = new Datastore({ projectId, keyFilename });
this.name = name;
this.instanceId = uuid();
console.log(`${packageName}/${this.constructor.name}: Creating Google Cloud Storage Instance for ${name}, assigning instanceId ${this.instanceId}`);
}
async init() {
}
async save(key, value) {
console.log(`${packageName}/${this.constructor.name}: Saving item with key ${key} and value ${JSON.stringify(value)}`);
await this.datastore.save({
key: this.datastore.key([this.name, key]),
data: { value },
});
}
async get(key) {
console.log(`${packageName}/${this.constructor.name}: Retrieving item with key ${key}`);
var item = await this.datastore.get(this.datastore.key([this.name, key]));
if (item[0])
return(item[0].value)
}
async delete(key) {
console.log(`${packageName}/${this.constructor.name}: Deleting item with key ${key}`);
await this.datastore.delete(this.datastore.key([this.name, key]));
}
async getAllItems() {
console.log(`${packageName}/${this.constructor.name}: Getting all items`);
var query = this.datastore
.createQuery(this.name);
var [entities, info] = await this.datastore.runQuery(query);
while (info.moreResults !== Datastore.NO_MORE_RESULTS) {
query = query.start(info.endCursor);
const [moreEntities, moreInfo] = await this.datastore.runQuery(query);
entities = entities.concat(moreEntities);
info = moreInfo;
}
for (var i = 0; i < entities.length; i++) {
entities[i].__key__ = entities[i][this.datastore.KEY];
delete entities[i][this.datastore.KEY];
}
return entities;
}
}
module.exports = GoogleCloudStorage;