Ember 3.25 не загружается

Я пытаюсь загрузить данные об отношениях из одного вызова API. У меня есть две мои модели, настроенные так:

Конкурсная модель (дочерняя, принадлежит):

import Model, { attr, belongsTo } from '@ember-data/model';

export default class ContestModel extends Model {
  @attr('date') createdAt;
  @attr('string') description;

  @belongsTo('brand', { inverse: 'contests' }) brand;
}

Модель бренда (родительский, hasMany):

import Model, { attr, hasMany } from '@ember-data/model';

export default class BrandModel extends Model {
  @attr('date') createdAt;
  @attr('string') name;

  @hasMany('contest') contests;
}

Я получаю через эту строку:

this.store.findRecord('contest', params.contest_id, { include: 'brand' });

Это возвращенная полезная нагрузка API:

{
  "data": {
    "type": "contest",
    "id": 1,
    "attributes": {
      "body_json": [
        {
          "question": "what time is it?",
          "answers": ["1PM", "2PM", "3PM", "4PM"]
        },
        {
          "question": "which collection is this artwork from?",
          "answers": ["botanical garden collection", "ghibli collection", "adventure collection", "swag collection"]
        }
      ],
      "created_at": "2021-05-23 18:00:00 -0700",
      "description": "a good description goes here"
    },
    "relationships": {
      "brand": {
        "links": {
          "self": "http://example.com/contests/2/relationships/brand" // not sure what this does
        },
        "data": { "type": "brand", "id": 2 }
      }
    },
    "links": {
      "self": "http://example.com/contests/2" // not sure how this is useful
    },
    "included": [
      {
        "id": 2,
        "type": "brand",
        "attributes": {
          "created_at": "2021-05-23 20:00:00 -0700",
          "name": "aloha vibe"
        }
      }
    ]
  }
}

Проблема здесь в том, что вызов myContest.brand возвращает объект Proxy, как в этом SO post< /а>.

Моя полезная нагрузка API неверна или что-то неправильно настроено для моих моделей? Или что-то другое? я на Ember 3.25.3

Обновление из комментариев: когда я добавляю async: false в запрос данных Ember, я получаю сообщение об ошибке после этой строки https://github.com/emberjs/data/blob/v3.25.0/packages/store/addon/-private/system/model/internal-model.ts#L705 из-за того, что toReturn.isEmpty верно. Разве я не настроил полезную нагрузку API? Не уверен, что не так. Кажется, ни createdAt, ни name не заполнены.

введите здесь описание изображения


person Sticky    schedule 25.05.2021    source источник
comment
Ожидается, что myContest.brand будет прокси. Поскольку запись уже находится в хранилище, вы должны иметь доступ к ее идентификатору (myContest.brand.id) или любому ее атрибуту (myContest.brand.name).   -  person jelhan    schedule 25.05.2021
comment
вы можете объявить async: false   -  person Lux    schedule 25.05.2021
comment
Я не могу вызвать myContest.brand.id без второго вызова API   -  person Sticky    schedule 26.05.2021
comment
Я добавил async: false, и теперь он говорит: Uncaught Error: Assertion Failed: You looked up the 'brand' relationship on a 'contest' with id 1 but some of the associated records were not loaded. Either make sure they are all loaded together with the parent record, or specify that the relationship is async (`belongsTo({ async: true })`)   -  person Sticky    schedule 26.05.2021
comment
Я обновил свой вопрос снимком экрана и оскорбительной строкой кода, вызвавшей исключение. Буду продолжать копать, но любые идеи определенно приветствуются!   -  person Sticky    schedule 26.05.2021


Ответы (1)


Ошибка найдена! Полезная нагрузка данных должна быть в следующем формате:

{
  "data": {
    "type": "contest",
    "id": 1,
    "attributes": {
      "body_json": [
        {
          "question": "what time is it?",
          "answers": ["1PM", "2PM", "3PM", "4PM"]
        },
        {
          "question": "which collection is this artwork from?",
          "answers": ["botanical garden collection", "ghibli collection", "adventure collection", "swag collection"]
        }
      ],
      "created_at": "2021-05-23 18:00:00 -0700",
      "description": "a good description goes here"
    },
    "relationships": {
      "brand": {
        "links": {
          "self": "http://example.com/brands/2"
        },
        "data": { "type": "brand", "id": 2 }
      }
    },
    "links": {
      "self": "http://example.com/contests/2"
    }
  },
  "included": [
    {
      "id": 2,
      "type": "brand",
      "attributes": {
        "created_at": "2021-05-23 20:00:00 -0700",
        "name": "aloha vibe"
      }
    }
  ]
}

Я вложил included в раздел data, но он должен быть на верхнем уровне с разделом data. Теперь все загружается правильно, и никаких дополнительных вызовов API не делается :)

person Sticky    schedule 25.05.2021