Models
AJAX Abstraction for a Single Resource
AJAX Abstraction for a Single Resource
This page describes how to update a resource using a Model.
Let's say you have an API endpoint located at http://localhost:1337/tweets
and that there is a tweet
you want to retrieve that looks like this:
{
id: 1,
text: 'An old tweet'
}
To update that Tweet, we need to issue a PUT
request to http://localhost:1337/tweets/1
, and include the properties we want to update in the body of the request like this:
PUT http://localhost:1337/tweets/1
{
text: 'A new tweet'
}
The code below demonstrates how to do that using a Model:
import { Model } from 'lore-models';
const Tweet = Model.extend({
urlRoot: 'http://localhost:1337/tweets'
});
const tweet = new Tweet({
id: 1,
text: 'Different text'
})
tweet.save()
First we import Model
from lore-models
. Then we create a new model called Tweet
, and provide the location of the API endpoint we want to interact with as the urlRoot
property.
Once we have the Tweet
model created, we create an instance of that model, and provide the properties for the model in the constructor. Then we called tweet.save()
to create that resource on in the API.
Because the instance we created has an id
, the tweet.save()
will be transformed into a PUT
request, and an AJAX request will be sent that looks like this:
PUT http://localhost:1337/tweets/1
{
"id": 1,
"text": "A new tweet"
}
The tweet.save()
method returns a promise. If you need access to the response object once the API call returns, you can do that using this code:
tweet.save().then(function(response) {
// do something with response
})
The response object will have a structure that looks like this:
const response = {
config: {
headers: {
Accept: "application/json, text/plain, */*"
},
method: "PUT",
responseType: "json",
url: "http://localhost:1337/tweets/1"
},
data: {
id: 1,
title: "Different text",
createdAt: "2016-07-02T00:00:06.407Z",
updatedAt: "2016-07-02T00:00:06.407Z"
},
headers: {
"content-type": "application/json"
},
request: {...}, // XMLHttpRequest
status: 200,
statusText: "OK"
};
Models use the axios library for handling for all network request, and that means the properties you set on models are ultimately just converted into a config object that axios
understands.
For the save()
method, that means the tweet.save()
call we demonstrated above is ultimately converted into this axios
call:
import axios from 'axios';
axios({
url: 'http://localhost:1337/tweets/1',
method: 'put',
headers: {
'Content-Type': 'application/json'
},
data: {
id: 1,
text: 'A new tweet'
}
})
If you need more control over your network requests, such as adding headers, simply provide an options
object to get tweet.destroy()
call like this:
tweet.save({
headers: {
'Content-Type': 'application/json'
Authorization: 'Bearer token'
}
})
This object will be passed directly to the axios
call.
You can learn about all of the config options that
axios
supports here.