node package manager
Easy collaboration. Discover, share, and reuse code in your team. Create a free org »

ananke

Ananke

Build Status Coverage Status

NodeJS datasource agnostic model, schema and validation layer

Defining a Schema

Schemas allow you to define the name and definition of the properties that make up your data structure. You can specify whether they are required, a data type (that automatically validates) as well as additional format, length, etc validators.

var CarSchema = new Ananke.Model.Schema({
    make: 'string',
    model: 'string',
    year: 'number',
    image: 'url',
    doors: 'number',
    drive: {
        type: 'string',
        validators: {
            inArray: [
                [ '2WD', '4WD', 'AWD' ]
            ]
        }
    }
});

Setting up a DataSource

DataSources are adapters that you pass in when creating a new Model that allow you to persist different Models to different types of backends and provides a consistent API for easier implementation.

var CarDataSource = new Ananke.DataSource.JSON('cars.json');

Creating a Model

Models are the main entry point to creating, fetching and validating data in your system. They hold your Schema and a DataSource adapter, as well as custom finders and additional logic to be provided to your Document classes that act as an instance of your model.

var Car = new Ananke.Model(CarSchema, CarDataSource);

Putting it all together

var CarSchema = new Ananke.Model.Schema({
    make: 'string',
    model: 'string',
    year: 'number',
    image: 'url',
    doors: 'number',
    drive: {
        type: 'string',
        validators: {
            inArray: [
                [ 'RWD', 'FWD', '4WD', 'AWD' ]
            ]
        }
    }
});
 
var CarDataSource = new Ananke.DataSource.JSON('cars.json');
 
var Car = new Ananke.Model(CarSchema, CarDataSource);
 
// Build a Jalopy 
var jalopy = Car.build({
    make: 'Ford',
    model: 'Pinto',
    year: 1971,
    image: 'http://www.trbimg.com/img-536a57b3/turbine/bonus.1976_ford_pinto_lyhbx2pd/1150/16x9',
    doors: 2,
    drive: 'RWD'
});
 
// Something a little nicer 
var porsche = Car.build({
    make: 'Porsche',
    model: 'Cayenne',
    year: 2013,
    image: 'http://www.blogcdn.com/www.autoblog.com/media/2012/09/2013-porsche-cayenne-s-diesel-paris.jpg',
    doors: 4,
    drive: '4WD'
});
 
// Find a car from our data source (Returns a then-able Promise) 
Car.findOne({ model: 'R8' })
.then(function(car) {
    console.log('Found %d %s %s', car.get('year'), car.get('make'), car.get('model'));
})
.catch(function(err) {
    console.log('There was a problem fetching the car: ', err.message);
});