Collections

AJAX Abstraction for Lists of Resources

parse

The parse() method provides a way to transform data provided to the collection before it's saved as the collections models.

Default Implementation

The default implementation looks like this:

parse: function(resp, options) {
  return resp;
},

Usage

Let's say you have an API endpoint located at http://localhost:1337/tweets, that returns a collection of tweets that looks like this:

[
  {
    id: 1,
    text: 'An old tweet'
  },
  {
    id: 2,
    text: 'A new tweet'
  }
]

If you wanted to retrieve those tweets, you could create this collection:

import { Collection } from 'lore-models';

const TweetCollection = Collection.extend({
  url: 'http://localhost:1337/tweets'
});

const tweets = new TweetCollection();

tweets.fetch();

Once the API call returns, tweet.toJSON() would look like this (exactly mirroring the API response):

[
  {
    id: 1,
    text: 'An old tweet'
  },
  {
    id: 2,
    text: 'A new tweet'
  }
]

But many APIs wrap the data they return in an object that contains metadata information for pagination, like this:

{
  data: [
    {
      id: 1,
      text: 'An old tweet'
    },
    {
      id: 2,
      text: 'A new tweet'
    }
  ],
  meta: {
    page: 1,
    pageSize: 5,
    nextPage: null
  }
}

In that case, the collection will need help in order to extract the array of tweets from the object returned by the API, and you do that by defining a custom parse() method, like this:

import { Collection } from 'lore-models';

const TweetCollection = Collection.extend({
  url: 'http://localhost:1337/tweets',

  parse: function(response){
    return response.data;
  }
});

const tweets = new TweetCollection();

tweets.fetch();

Whatever the API returns will be passed to parse() as response, and whatever that function returns will be saved as the array of models for the collection.

So now, even though the API response is no longer an array, calling tweets.toJSON() will still return this:

[
  {
    id: 1,
    text: 'An old tweet'
  },
  {
    id: 2,
    text: 'A new tweet'
  }
]

That's the normal use for parse() - transforming data returned from an API endpoint. But the method will also be invoked when creating a collection, if you provide it with data yourself, like this:

import { Collection } from 'lore-models';

const TweetCollection = Collection.extend({
  url: 'http://localhost:1337/tweets',

  parse: function(response){
    return response.data;
  }
});

const tweets = new TweetCollection({
  data: [
    {
      id: 1,
      text: 'An old tweet'
    },
    {
      id: 2,
      text: 'A new tweet'
    }
  ],
  meta: {
    page: 1,
    pageSize: 5,
    nextPage: null
  }
});

If we were to examine tweets.toJSON() at this point, it would return exactly the same result as it did when we got the data from the API:

[
  {
    id: 1,
    text: 'An old tweet'
  },
  {
    id: 2,
    text: 'A new tweet'
  }
]