Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add payload in Ember deleteRecord

I have a requirement to include remarks from user in the payload whenever he tries to delete an item. So far, I have this:

let remarks = this.get('remarks');
let id = this.get('itemID');

this.store.findRecord('item', id).then(function (selectedItem) {

    // TODO - DELETE doesn't accept payload in body?

    selectedItem.destroyRecord({remarks:remarks}).then(function(response){

        Ember.debug('delete successful:'+JSON.stringify(response));

        Ember.$('#confirmDelete').modal('hide');
        Ember.$('#remarks').val('');

        context.set('successful', true);
        context.set('message', context.get('i18n').t('success.role.delete'));                        

    }).catch(function(error){
        Ember.debug('delete failed:'+JSON.stringify(error));

        Ember.$('#confirmDelete').modal('hide');
        Ember.$('#remarks').val('');

        context.send('showErrors', error);
    });
});                 

It doesn't work. So does setting the remarks value in the model like:

...
this.store.findRecord('item', id).then(function (selectedItem) {

    selectedItem.set('remarks', remarks);

    selectedItem.destroyRecord().then(function(response){
...

I am trying to override the deleteRecord but I don't know where to start or how to do it.

Anyone have ideas? Thanks!

like image 871
yojoannn Avatar asked Mar 05 '16 21:03

yojoannn


1 Answers

You can easily achieve this kind of behaviour by extending your application adapter with the following mixin:

/* app/mixins/delete-with-playload.js */

import Ember from 'ember';

export default Ember.Mixin.create({
  deleteRecord(store, type, snapshot) {
    var id = snapshot.id;
    var data = {};
    var serializer = store.serializerFor(type.modelName);

    serializer.serializeIntoHash(data, type, snapshot);

    return this.ajax(this.buildURL(type.modelName, id, snapshot, 'deleteRecord'), "DELETE", {
      data
    });
  }
});

Then just add it to your application adapter

/* app/adapters/application.js */

import RestAdapter from 'ember-data/adapters/rest';
import DeleteWithPayloadMixin from '../mixins/delete-with-payload';
export default RestAdapter.extend(DeleteWithPayloadMixin);

This will result a payload identical to the payload of PUT method, meaning a payload of the form:

{
  "<model-name>": {
    // model's serialized attributes
  }
}

Now all you have to do is to set the desired attributes on the record before deleting, and destroy the record.

model.setProperties({
  deleteReason: 'whatever'
});
model.destroyRecord();
/* 
results a DELETE request when requestBody is "{
  "<model-name>": { 
    ... 
    "deleteReason": "whatever"
    ...
  }
}"
*/
like image 160
Ramy Ben Aroya Avatar answered Sep 30 '22 18:09

Ramy Ben Aroya