Models

AJAX Abstraction for a Single Resource

urlRoot

The urlRoot is the location of the API endpoint used for fetching, creating, updating, or deleting the resource associated with this model.

This property can be either a string or a function that returns a string.

Default Implementation

The default implementation looks like this:

urlRoot: '',

The equivalent function version would look like this:

urlRoot: function() {
  return '';
},

Usage

A common use for this method is to construct nested URLs.

Many REST API endpoints have flat URLs, like /tweets or /users. But some APIs require you to use a nested URL structure like /users/1/tweets/1 when fetching or updating data.

The code below shows how you can use initialize() and urlRoot() to accomplish this:

import { Model } from 'lore-models';

const Tweet = Model.extend({
  initialize: function(attributes, options){
    this.user = options.user;
  },

  urlRoot: function() {
    return `http://localhost:1337/users/${this.user}/tweets`
  }
})

const tweet = new Tweet({
  id: 1
}, {
  user: 1
})

tweet.fetch()

In the code above, we're providing a second argument to new Tweet(), and that additional information is passed to initialize() as options, where we save the id for the user.

Then we override the urlRoot(), and provide method to compose the nested URL endpoint using the user.

When we call tweet.fetch() it will make an API call to http://localhost:1337/users/1/tweets/1, and you can confirm the url it will use by calling tweet.url().

The final URL is constructed by the url() method, which you can read more about here.