z80crew
z80crew

Reputation: 1200

Ember JS: Passing parameters to Model.save() for custom API

I'm working on an Ember.js application using Ember Data on a somewhat unusual JSON API.

To query an item from that API the URL looks like /singleitem?collection_id=1&item_id=2 To fetch the data I'm using this model hook:

import Route from '@ember/routing/route';
export default Route.extend({
    model(params) {
        return this.store.query('singleitem', {item:params.item_id, collection:params.collection_id});
    }
});

In a component I show data from the API in an <input type="text"> field and when the user changes the content I want the component to update my model and write it back to my API:

import Component from '@ember/component';
export default Component.extend({
    async change() {
        this.test.set('title', 'Hello World!');
        await this.test.save();
    }
});

This code sends a PATCH request to /singleitem/2 where 2 is the 'id' property from the response of the JSON API item.

How can I pass parameters to save() so that the PATCH request is sent to /singleitem?collection_id=1&item_id=2 – just like I've been able to do in this.store.query?

Upvotes: 1

Views: 721

Answers (1)

ykaragol
ykaragol

Reputation: 6221

If you want to modify the url of any operation, then you need to modify your adapter. If you are using the default adapter, you need to create one for your entity. See from Ember Guide

RESTAdapter and JSONAPIAdapter have methods to modify each type of request's endpoints, such as: urlForUpdateRecord, urlForQuery etc.

I think what you need is to modify urlForUpdateRecord. Such as:

urlForUpdateRecord(id, modelName, snapshot) {
  const collectionId = 1;
  // you need to change with correct value of `collectionId`

  return `?collection_id=${collectionId}&item_id=${id}`;
}

Upvotes: 2

Related Questions