Search code examples
ember-data

Ember JSON API Adapter - customise request URL using dynamic param


When the action below is called in a route, the default the Ember JSON API Adapter will send a PATCH request to ${HOST}/${NAMESPACE}/${MODEL}/${ID}.

saveChanges: function(record) {
  return record.save();
},

I would like to be able to send a single PATCH request to ${HOST}/${NAMESPACE}/${MODEL}/************/${ID} where the value of ************ can be passed to the action as a dynamic parameter when calling record.save().

Is there any way to do this using the JSONAPI adapter, or do I have to just use a vanilla AJAX request?


Solution

  • You could customize your application- or model-adapter

    ember generate adapter application
    

    or

    ember generate adapter model-name
    

    app/adapters/application.js or app/adapters/model-name.js

    import DS from 'ember-data';
    
    export default DS.JSONAPIAdapter.extend({
        namespace: 'api',
    
      urlForUpdateRecord(id, modelName, snapshot) {
        let originalUpdateURL = this._super(...arguments);
    
        let { adapterOptions } = snapshot;
        if (adapterOptions && adapterOptions.customString) {
          let modelPath = this.pathForType(modelName);
          return originalUpdateURL.replace(`/${modelPath}/`, `/${modelPath}/${adapterOptions.customString}/`);
        }
        return originalUpdateURL;
      }
    
    });
    

    after that you can call save-method of your model with adapterOptions passed:

    this.get('model').save({
      adapterOptions: { customString: 'hello-world' }
    });
    

    after that your patchURL will look like: /api/your-model/hello-world/1