Skip to content

Instantly share code, notes, and snippets.

@kixxauth
Created March 8, 2011 15:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kixxauth/860379 to your computer and use it in GitHub Desktop.
Save kixxauth/860379 to your computer and use it in GitHub Desktop.
Simple JS data modeling
var db = require('db');
var assert = require('assert');
var Q = require('q');
function hash() {
// Hashing function used to make keys etc.
}
var Story = db.Model('Story', {
title: db.StringProperty()
, summary: db.StringProperty()
, pub_date: db.IntegerProperty()
, url: db.StringProperty({required: true})
// Required function which creates a unique key for this model.
// The returned key must be something sensible.
, key: function (self) {
return hash(self.url);
}
});
var article = Story({title: 'Balmer fired from Microsoft'});
assert.equal(article.title, 'Balmer fired from Microsoft');
assert.equal(typeof article.summary, 'undefined');
article.pub_date = new Date().getTime();
// Methods are called by their string names, keeping the namespace open for
// more properties and the implementation simpler.
var json_repr = article('json'); // Output JSON representation.
// Async actions return a promise.
Q.when(article('put'), function (article) {
console.log('article has been written to disk');
key = article('key'); // Special method to get a key
// Output the key string to the UI or something
});
// Some time later you can do a get by key
var key;
var article = db.get(key);
// Properties are just properties.
assert.equal(article.pubdate, 1234567890);
// Queries
// Get a query object and call methods on it. It works like jQuery.
var query = db.Query()
// The type name passed as the first argument to the model when this entity was created.
.type('Story')
// Check for a property and get a pointer to it.
.has('pub_date')
// The greater than function
.gt(1234567790);
// Query ojects will need an index created for them before they execute, or
// create one on the fly if one does not already exist.
Q.when(query.fetch(), function (results) {
assert.ok(Array.isArray(results));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment