Sync

Method responsible for making AJAX Calls

Introduction

Sync is the method that's actually responsible for making AJAX calls, and it uses axios to do that.

While it's rare that you would need to interact with this method directly, as the Model methods for save(), update(), and destroy() invoke it automatically, there are two scenarios where it's useful to interact with directly:

  • Sometimes APIs make breaking changes, like renaming an attribute, and it can be a lot of work to find and replace all references to the old attribute, and test the application to make sure it still works correctly.

    In this scenario you can use parse() to rename the new attribute back to the original name, but if you ever need to save changes to that attribute, the API won't see the change, because the you'll be sending back the original (no longer recognized) name.

    In this scenario, you need to map the original name back to the new name, and you can use sync() to do this.

    Combining the usage of parse() and sync() in this manner allow you to create a complete buffer between the API and your application, and transform properties back and forth however you need.

  • You can also use this method to inspect the response object before the application gets it, This can be useful if you need to make a decision based on the status code of the response, like logging the user out if any request returns a 401 (suggesting their token expired), or if you just want to observe and log all network requests.

Example Usage

To illustrate how to use sync(), the examples below assume a Tweet model has been created like this:

import { Model, syc } from 'lore-models';

const Tweet = Model.extend({
  urlRoot: 'http://localhost:1337/tweets'
})

Create

This code will create a tweet, and is similar to calling tweet.save() when the model instance has no id:

const tweet = new Tweet({
  text: 'A new tweet'
})

sync('create', model).then(function(response){
 // inspect the response
})

Update (PUT)

This code will update a tweet, and is similar to calling tweet.save() when the model instance has an id:

const tweet = new Tweet({
  id: 1,
  text: 'A new tweet'
})

sync('update', model).then(function(response){
 // inspect the response
})

Update (PATCH)

This code will update a tweet, but using PATCH instead of PUT, and is similar to calling tweet.save({ patch: true }) when the model instance has an id:

const tweet = new Tweet({
  id: 1,
  text: 'A new tweet'
})

sync('patch', model).then(function(response){
 // inspect the response
})

Delete

This code will delete a tweet, and is similar to calling tweet.destroy():

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

sync('delete', model).then(function(response){
 // inspect the response
})

Retrieve

This code will retrieve a tweet, and is similar to calling tweet.fetch():

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

sync('read', model).then(function(response){
 // inspect the response
})