Models
AJAX Abstraction for a Single Resource
AJAX Abstraction for a Single Resource
The parse()
method provides a way to transform data provided to the model before it's saved as the model's attributes
.
The default implementation looks like this:
parse: function(response) {
return response;
},
Let's say you have an API endpoint located at http://localhost:1337/tweets/1
, that returns a tweet that looks like this:
{
id: 1,
text: 'An old tweet'
}
If you wanted to retrieve that tweet, you could create this model:
import { Model } from 'lore-models';
const Tweet = Model.extend({
urlRoot: 'http://localhost:1337/tweets'
});
const tweet = new Tweet({
id: 1
});
tweet.fetch();
Once the API call returns, tweet.attributes
would look like this (exactly mirroring the API response):
{
id: 1,
text: 'An old tweet'
}
Sometimes you might want to transform that data though, such as changing the name or value of a property, or adding a new field, which can be a quick way to resolve breaking API changes.
You can do that by defining a parse()
like this:
import { Model } from 'lore-models';
const Tweet = Model.extend({
urlRoot: 'http://localhost:1337/tweets',
parse: function(response){
response.message = response.text;
return response;
}
});
const tweet = new Tweet({
id: 1
});
tweet.fetch();
Whatever the API returns will be passed to parse()
as response
, and whatever that function returns will be saved as the model's attributes
. In the code above, we're copying the value of text
onto a new attribute called message
.
This time, once the API call returns, tweet.attributes
will look like this:
{
id: 1,
text: 'An old tweet',
message: 'An old tweet'
}
That's the normal use for parse()
- transforming data returned from an API endpoint. But sometimes it's useful to create a model and parse the data provided to it. By default this does not happen.
For example, take a look at the code below:
import { Model } from 'lore-models';
const Tweet = Model.extend({
urlRoot: 'http://localhost:1337/tweets',
parse: function(response){
response.message = response.text;
return response;
}
});
const tweet = new Tweet({
id: 1,
text: 'An old tweet'
});
If we were to examine tweet.attributes
at this point, they would look like this, mirroring the data we provided to the constructor:
{
id: 1,
text: 'An old tweet'
}
If we wanted the model to parse that data, we need to tell it to by providing an options object, like this:
const tweet = new Tweet({
id: 1,
text: 'An old tweet'
}, {
parse: true
});
Here we've provided an options
object as a second argument to the constructor, and set parse
to true
. This time tweet.attributes
will look like this:
{
id: 1,
text: 'An old tweet',
message: 'An old tweet'
}
Now the data will mirror what we would have gotten by calling the API endpoint.