lundi 28 décembre 2020

Ember Data JSON API - How to make a PATCH request using a related links URL

Ember version: 3.23

Ember Data: 3.23

I want to patch a relationship by making a request to the URL provided in the links object in the resources relationships:

{
  "type": "appointments",
  "id": "1",
  "attributes": {},
  "relationships": {
    "status": {
      "links": {
        "self": "/api/appointments/1/relationships/status",
        "related": "/api/appointments/1/status"
      },
      "data": {
        "type": "statuses",
        "id": "1"
      }
    }
  }
}

Given the above I want to issue the PATCH /api/appointments/1/relationships/status request.

// model/appointment.js
import Model, { attr, belongsTo, hasMany } from '@ember-data/model';
export default class AppointmentModel extends Model {
  @belongsTo('status') status;
};
// model/status.js
import Model, { attr, hasMany } from '@ember-data/model';
export default class StatusModel extends Model {
  @hasMany('appointment') appointments;
  @attr('string') name;
}

What I'm trying to do is:

const appointment = this.store.findRecord('appointment', id);
appointment.status = newStatus;
return appointment.get('status').save();

However the above returns an error saying save() is not a function on the status object (the status object is a ember Proxy object).

I know I can do:

const status = this.store.peekRecord('status', appointment.get('status.id'));
return status.save();

But no, that is not what I want to request. That would make a request to /api/statuses/1, which has no context of an appointment, the primary resource.

I also know that I can just save the appointment and get the relationship updates, but that would make the links I've setup completely useless. I want to be able to request the links I've setup for the relationships.

Essentially I want to be able to follow this part of the JSON:API spec: Updating Relationships.

How can I make a save() request to a relationship which uses the relationship links?




Aucun commentaire:

Enregistrer un commentaire