Models

AJAX Abstraction for a Single Resource

delete

This page describes how to delete a resource using a Model.

Basic Usage

Let's say you have an API endpoint located at http://localhost:1337/tweets and that there is a tweet you want to delete that looks like this:

{
  id: 1,
  text: 'An old tweet'
}

To delete that Tweet, we need to issue a DELETE request to http://localhost:1337/tweets/1, that looks like this:

DELETE http://localhost:1337/tweets/1

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
})

tweet.destroy()

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 id of the resource we want to delete. Then we call tweet.destroy() to delete that resource through the API.

The tweet.destroy() will be transformed into a DELETE request, and an AJAX request will be sent that looks like this:

DELETE http://localhost:1337/tweets/1

The tweet.destroy() 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.destroy().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: "DELETE",
    responseType: "json",
    url: "http://localhost:1337/tweets/1"
  },
  data: {},
  headers: {
    "content-type": "application/json"
  },
  request: {...}, // XMLHttpRequest
  status: 204,
  statusText: "NO CONTENT"
};

Advanced Usage

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 destroy() method, that means the tweet.destroy() call we demonstrated above is ultimately converted into this axios call:

import axios from 'axios';

axios({
  url: 'http://localhost:1337/tweets/1',
  method: 'delete',
  headers: {
    'Content-Type': 'application/json'
  }
})

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.destroy({
  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 axiossupports here.