Skip to content

Relational Resources

Marak edited this page Aug 23, 2012 · 1 revision

All the below examples use couchdb engine. These examples implements a one-to-many relationship between user and repository

Define resources

user.js

var resourceful = require('resourceful');

module.exports = resourceful.define('user', function () {
  this.string('name')
});

repository.js

var resourceful = require('resourceful');

module.exports = resourceful.define('repository', function () {
  this.parent('User');
});

Creating parent

var User = require('./user');

User.create({
  id: 'marak',
  name: 'Marak Squires'
}, function (err, user) {
  console.log(user);
  /*
  {
    id: 'marak',
    name: 'Marak Squires',
    resource: 'User',
    repository_ids: []
  }
   */
});

The document is stored in couchdb as following:

[
  {
    _id: 'user/marak',
    name: 'Marak Squires',
    resource: 'User',
    repository_ids: []
  }
]

Creating child

Creating a child will prepend the parent's id to allow multiple child resources with the same id but in diffirent parent's context.

var User = require('./user');

User.createRepository('marak', {
  id: 'colors',
}, function (err, repo) {
  console.log(repo);
  /*
  {
    id: 'user/marak/colors',
    resource: 'Repository',
    user_id: 'marak'
  }
   */
});

This will add 'colors' to marak's repository_ids making the documents stored in couchdb as

[
  {
    _id: 'user/marak',
    name: 'Marak Squires',
    resource: 'User',
    repository_ids: ['colors']
  },
  {
    _id: 'repository/user/marak/colors'
    resource: 'Repository',
    user_id: 'marak'
  }
]

The child can be requested using the Repository resource, but you need to provide the parent context too.

var Repository = require('./repository');

Repository.get('user/marak/colors', function (err, repo) {
  console.log(repo);
  /*
  {
    id: 'user/marak/colors',
    resource: 'Repository',
    user_id: 'marak'
  }
   */
});

Fetching children

All the children of a parent can be fetched using the following

var User = require('./user');

User.repositories('marak', function (err, repos) {
  console.log(repos);
  /*
  [
    {
      id: 'user/marak/repository',
      resource: 'Repository',
      user_id: 'marak'
    }
  ]
  */
});

Destroying a parent

The destruction of a parent will result in cascading destruction of it's children. Cascading destruction here means that all the children of the parent's children will be destroyed and so on.

var User = require('./user');

User.destroy('marak', function () {});

Both the documents in couchdb will be destroyed by the above call.