AmpersandJS / ampersand-rest-collection

ampersand-collection with REST and lodash mixins for easy use with REST APIs.
http://ampersandjs.com/docs#ampersand-rest-collection
MIT License
23 stars 11 forks source link

ampersand-rest-collection

Extends ampersand-collection with REST and Lodash mixins.

This makes ampersand-collection work and act a lot like Backbone.Collection, if youre planning on hitting a REST-ful API this is probably what you want to use.

Part of the Ampersand.js toolkit for building clientside applications.

Install

npm install ampersand-rest-collection

example

Define a collection

var Collection = require("ampersand-rest-collection");
var Model = require("some-model");

module.exports = Collection.extend({
    model: Model,
    url: "/models"
});

Using it:

var Collection = require("./path-to-your-collection-module");

var c = new Collection();

// call RESTful methods
c.fetch();

// also has lodash mixins
c.each(function (model) {
    console.log("model:", model);
});

API Reference

The ampersand-rest-collection is simply an ampersand-collection extended with two mixins: ampersand-collection-rest-mixin and ampersand-collection-lodash-mixin.

var Collection = require("ampersand-collection");
var lodashMixin = require("ampersand-collection-lodash-mixin");
var restMixins = require("ampersand-collection-rest-mixin");

module.exports = Collection.extend(lodashMixin, restMixins);

ajaxConfig AmpersandRestCollection.extend({ ajaxConfig: function () { ... } })

ampersand-sync will call ajaxConfig on your collection before it makes the request to the server, and will merge in any options you return to the request. When extending your own collection, set an ajaxConfig function to modify the request before it goes to the server.

ajaxConfig can either be an object, or a function that returns an object, with the following options:

var MyCollection = AmpersandRestCollection.extend({
    url: 'http://otherdomain.example.com/stuff',

    ajaxConfig: function () {
        return {
            headers: {
                'Access-Token': this.accessToken
            },
            xhrFields: {
                withCredentials: true
            }
        };
    }
});

var collection = new MyCollection()
collection.fetch();

fetch collection.fetch([options])

Fetch the default set of models for the collection from the server, setting them on the collection when they arrive. If the collection already contains data, by default, the operation of set will add new models from the server, merge the attributes of existing ones, and remove any which aren't in the response. This behaviour can be modified with the reset, add, remove, merge options.

Options:

You can also pass any options that xhr expects to modify the query. For example: to fetch a specific page of a paginated collection: collection.fetch({ data: { page: 3 } })

getOrFetch collection.getOrFetch('id', [options], callback)

Convenience method. Gets a model from the server or from the collection if a model with that id already exists.

By default it will only fetch and add the model with the id you pass in.

collection.getOrFetch('42', function (err, model) {
    if (err) {
        console.log('handle');
    } else {
        // `model` here is a fully inflated model
        // It gets added to the collection automatically.
        // If the collection was empty before, it's got 1
        // now.
    }
});

If you pass {all: true} it will fetch the entire collection (by calling its fetch method) and then do a get to attempt to pull out the model by the id you specified.

collection.getOrFetch('42', {all: true}, function (err, model) {
    if (err) {
        console.log('handle');
    } else {
        // `model` here is a fully inflated model
        // It gets added to the collection automatically.
    }
});

fetchById collection.fetchById('id', callback)

Fetches and adds a model by id to the collection. This is what getOrFetch uses if it doesn't have a model already.

collection.fetchById('42', function (err, model) {
    // returns inflated, added model with a `null` error
    // or an error object.
});

create collection.create(model, [options])

Convenience to create a new instance of a model within a collection. Equivalent to instantiating a model with a hash of attributes, saving the model to the server, and adding the model to the set after being successfully created. Returns the new model. If client-side validation failed, the model will be unsaved, with validation errors. In order for this to work, you should set the model property of the collection. The create method can accept either an attributes hash or an existing, unsaved model object.

Creating a model will cause an immediate "add" event to be triggered on the collection, a "request" event as the new model is sent to the server, as well as a "sync" event, once the server has responded with the successful creation of the model. Pass {wait: true} if you'd like to wait for the server before adding the new model to the collection.

var Library = AmpersandRestCollection.extend({
  model: Book
});

var library = new Library;

var othello = library.create({
  title: "Othello",
  author: "William Shakespeare"
});

sync model.sync(method, collection, [options])

Simple delegation to ampersand-sync to persist the collection to the server. Can be overridden for custom behaviour.

lodash methods (42)

The ampersand-collection-lodash-mixin proxies the collection methods in lodash onto the underlying models array for the collection. For example:

books.each(function(book) {
  book.publish();
});

var titles = books.map(function(book) {
  return book.get("title");
});

var publishedBooks = books.filter(function(book) {
  return book.get("published") === true;
});

var alphabetical = books.sortBy(function(book) {
  return book.author.get("name").toLowerCase();
});

The full list of proxied methods is:

credits

If you like this follow @HenrikJoreteg on twitter.

license

MIT