Skip to content

Instantly share code, notes, and snippets.

@xemasiv
Last active April 5, 2018 18:48
Show Gist options
  • Save xemasiv/86a8bb9312f6e9894fea638b75453487 to your computer and use it in GitHub Desktop.
Save xemasiv/86a8bb9312f6e9894fea638b75453487 to your computer and use it in GitHub Desktop.
DataStoreReader - Google Cloud Datastore Query Wrapper

Summary:

  • Returns a promise so it's predictable and easier to work with
  • Destructuring of entities
  • Destructuring of keys
  • Destructuring of endCursor (for Pagination support)
  • Support for SELECT, FILTER and LIMIT
  • Support for ORDER, as replaced with ASCEND and DESCEND for readability
  • Queries are chainable of course
const Reader = new DataStoreReader('Inventory');
Reader
  .FILTER('current_amount', '=', '0')
  .LIMIT(5)
  .RUNQUERY()
  .then(()=>{
    // do your magic
  })
  .catch(()=>{
    // do your magic
  });

Files:

  • index.js - DataStoreReader setup & class itself
  • test.js - Test example

Notes

// Setup
process.env["GOOGLE_APPLICATION_CREDENTIALS"] = __dirname.concat("/google_datastore/XYZ.json");
const GoogleDatastore = require('@google-cloud/datastore');
const Datastore = new GoogleDatastore({
projectId: 'XYZ'
});
// Class itself
class DataStoreReader{
constructor (kind, endCursor) {
let query = Datastore.createQuery(kind);
if (Boolean(endCursor) === true) {
query = query.start(endCursor);
}
this.query = query;
}
ASCEND (a) {
this.query = this.query.order(a);
return this;
}
DESCEND (a) {
this.query = this.query.order(a, {
descending: true,
});
return this;
}
SELECT (a) {
this.query = this.query.select(a);
return this;
}
FILTER (a, b, c) {
this.query = this.query.filter(a, b, c);
return this;
}
LIMIT (a) {
this.query = this.query.limit(a);
return this;
}
RUNQUERY () {
return new Promise((resolve, reject)=>{
Datastore
.runQuery(this.query)
.then((results)=>{
let entities = results[0];
let keys = entities.map(entity => entity[Datastore.KEY]);
let info = results[1];
let endCursor = (
info.moreResults !== Datastore.NO_MORE_RESULTS ?
info.endCursor :
null
);
resolve({entities, keys, endCursor});
})
.catch(reject);
});
}
};
console.log('TESTING');
const testLoop = (endCursor) => {
const Reader = new DataStoreReader('XYZ_KIND', endCursor);
Reader
// .FILTER('xyz_column_name', '=', '123')
// .ASCEND('xyz_column_name')
// .DESCEND('xyz_column_name')
// .SELECT(['xyz_column_name'])
// .LIMIT(3)
.RUNQUERY()
.then(({entities, keys, endCursor})=>{
console.log('entities:', entities.length, entities);
console.log('keys:', keys.length, keys);
console.log('endCursor:', endCursor);
if (endCursor) {
testLoop(endCursor);
}
})
.catch(console.log);
}
testLoop();
@xemasiv
Copy link
Author

xemasiv commented Apr 5, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment