holidayextras / jsonapi-client

Easily consume a json:api service in Javascript.
MIT License
68 stars 19 forks source link

Resource.relationships('my-rel').add(related) re-initialise the relationship #48

Open danielebriggi opened 8 years ago

danielebriggi commented 8 years ago

As shown in the snipped below, adding related resources to the main resource in this way, the relationship is always re-initialised:

    $.each(related, function () {
        res.relationships('my-rel').add(this);
    });

Is this an expected behaviour? I think that this piece of code from the method Resource.prototype.relationships should also check the existence of the relationship before initialise it.

  if (!self._base.id) {
    rawRelation = this._raw.relationships[relationName] = {
      meta: { _trust: true },
      links: { },
      data: null
    };
  }
theninj4 commented 8 years ago

Ah, yes, this is an interesting one. This check if (!self._base.id) { is there to solve a peculiar edge case. If you create a new resource locally, and you do NOT sync it before you try and alter the relationships, then we don't know what kind of relationship it's meant to be. It's only after the resource has been created in the remote service that it'll be given a real id and we can infer the type of the relationship (is it a one or many?).

I think you're right that if we don't have a remote id and we've already initialised the relationship, we should avoid re-initialising it :+1: