Search code examples
jsonhttpember.jsember-datajson-patch

ember-data and json-patch requests


Can ember-data send json-patch PATCH on model.save() call? (with media type application/json-patch+json RFC6902)

The documentation says yes but with no details:

https://guides.emberjs.com/release/models/creating-updating-and-deleting-records/#toc_persisting-records

Testing it shows PUT requests with the entire model in the request.


Solution

  • I suspect your application uses the RESTAdapter and not the JSONAPIAdapter.

    RESTAdapter was the default adapter before Ember Data 2.0 as stated here

    You can take a look a both adapters updateRecord methods:

    RestAdapter

    /**
        Called by the store when an existing record is saved
        via the `save` method on a model record instance.
        The `updateRecord` method serializes the record and makes an Ajax (HTTP PUT) request
        to a URL computed by `buildURL`.
        See `serialize` for information on how to customize the serialized form
        of a record.
        @method updateRecord
        @param {Store} store
        @param {Model} type
        @param {Snapshot} snapshot
        @return {Promise} promise
      */
      updateRecord(store, type, snapshot) {
        const data = serializeIntoHash(store, type, snapshot, {});
    
        let id = snapshot.id;
        let url = this.buildURL(type.modelName, id, snapshot, 'updateRecord');
    
        return this.ajax(url, 'PUT', { data });
      }
    

    JSONAPIAdapter

    updateRecord(store, type, snapshot) {
        const data = serializeIntoHash(store, type, snapshot);
    
        let url = this.buildURL(type.modelName, snapshot.id, snapshot, 'updateRecord');
    
        return this.ajax(url, 'PATCH', { data: data });
      }
    

    As you can see, one uses PUT, the other PATCH. The JSONAPIAdapter is now the default one, that's why the documentation deals with PATCH requests.

    If you want to use PATCH instead of PUT and keep RestAdapter, you should extend from RestAdapter and modify the updateRecord method :D

    I hope it will find you well ;)