ken
ken

Reputation: 9013

Intercepting a REST call with Ember Data

For a particular REST server that I'm working against the DELETE method has two varieties. When called without a query parameter the delete action results in an update taking place where the underlying resource's workflow status is "marked for deletion". If, however, an immediate deletion is the goal than you simply add the query parameter ?immediate=true.

I'd to programmatically send choose which of these varieties to send based on some simple client side logic but I'm not sure how I would get my query parameter added to the DELETE request.

In both cases, I'm assuming that calling DS.Model's .destroyRecord() or .deleteRecord() is appropriate. I'm also wondering if this is a case where I would need to create a custom DS.Adapter. I'd love to avoid that but if I must do it are there any good examples of this? Is there a way to inherit the implementation of all adapter methods and only override what needs changing (the documentation indicated that DS.Adapter is purely abstract)?

Upvotes: 2

Views: 533

Answers (1)

TrevTheDev
TrevTheDev

Reputation: 2737

One solution would be to to override the RESTAdapter:

App.ProductAdapter = DS.RESTAdapter.extend({

   deleteRecord: function(store, type, record) {
     //do ajax stuff here

     //return a promise that resolves or rejects based on ajax outcomes
     return new Em.RSVP.Promise( function(resolve, reject){ resolve(); } );
   },

})

The following is not required but I use it to wrap my ajax request in a promise:

function ajaxPromise (url, type, hash) {
    return new Ember.RSVP.Promise(function(resolve, reject) {
        hash = hash || {};
        hash.url = url;
        hash.type = type;
        hash.dataType = 'json';
        hash.success = function(json) {
            Ember.run(null, resolve, json);
        };
        hash.error = function(json) {
           if (json && json.then) { json.then = null }
           Ember.run(null, reject, json);
        };
    $.ajax(hash);
    });
}

You can then pass it type DELETE with any additional parameters in the hash or add them to the URL. e.g.

deleteRecord: function(store, type, record) {
   var promise = new ajaxPromise(URL, "DELETE", hash);
   promise.then(function(result){
     //do stuff here with result
   });
   return promise
}

Upvotes: 1

Related Questions