mardi 9 juin 2020

Ember sideload data not linked

I'm new to using Ember and was assigned to an ongoing project and need to resolve the following:

export default class OrderModel extends Model.extend(LoadableModel) {
  @attr('string') status;
  @attr('number') total;
  @hasMany('order-item', { async: true }) orderItems;
}

export default class OrderItemModel extends Model.extend(LoadableModel) {
  @attr('number', { defaultValue: 0 }) discount;
  @attr('number', { defaultValue: 0 }) price;
  @hasMany('item-fix', { async: false }) fixes;
}

export default class ItemFixModel extends Model.extend(LoadableModel) {
  @attr('number', { defaultValue: 0 }) price;
}

and when I do let order = await this.store.findRecord('order', order_id, { reload: true }); the json response is:

data: {
  type: "orders",
  id: "1584",
  attributes: {
    status: "in_progress",
    total: 1300
  },
  relationships: {
    order-items: {
      data: [
        {
          type: "order-items",
          id: "1801
        }
      ]
    }
  }
},
included: [
  {
    type: "order-items"
    id: "1801",
    attributes: {
      discount: 0,
      price: 1200
    },
    relationships: {
      item-fixes: {
        data: [
          {
            type: "item-fixes",
            id: "335"
          }
        ]
     }
  },
  {
    type: "item-fixes",
    id: "335",
    attributes: {
      price: 100
    }
  }
]

but when I inspect the orderItem inside the order variable, the itemFixes are empty, but the is in the sideload of the response.

¿How can I link this nested relationship?

Also, here is the serializer.

export default DS.JSONAPISerializer.extend({
  serialize(snapshot) {
    let serialized = this._super(...arguments);
    let { adapterOptions } = snapshot;

    if (adapterOptions && adapterOptions.addPromotionCode) {
      return { code: serialized.data.attributes.code }
    }

    serialized.included = A([]);
    snapshot.eachRelationship((key, relationship) => {
      if (relationship.kind === 'belongsTo') {
        if (!isBlank(snapshot.belongsTo(key))) {
          let node = snapshot.belongsTo(key).record.serialize({ includeId: true }).data;
          delete node.relationships;
          serialized.included.pushObject(node);
        }
      } else if (relationship.kind === 'hasMany') {
        if (!isBlank(snapshot.hasMany(key))) {
          snapshot.hasMany(key).forEach(ele => {
            let node = ele.record.serialize({ includeId: true }).data;
            delete node.relationships;
            serialized.included.pushObject(node);
          });
        }
      }
    });

    return serialized;
  }
});



Aucun commentaire:

Enregistrer un commentaire