Quantcast
Channel: Ember.JS - Latest topics
Viewing all articles
Browse latest Browse all 4830

Fetching child records for non-JSON API compliant endpoints

$
0
0

@williamhaley wrote:

My API currently structures data like this.

Authors: [
  { id: 1, name: 'Jane Austen' },
  { id: 2, name: 'Stephen King' }
]
Books: [
  { id: 1, author-id: 1, title: 'Pride & Prejudice' },
  { id: 2: author-id: 2, title: 'IT' },
  { id: 3, author-id: 2, title: 'Cujo' }
]

The child records (sub-records? sub-models? child relationships? Not sure what the best term is) have references to the parent records, and not the other way around. This sort of reverse referenced relationship doesn't seem to jive well with Ember.

I'm trying to figure out if there's any way to easily fetch the child books when running a store.findAll('author') in Ember. Ideally, my authors would all come back with their respective embedded books for use in my template.

Right now, I'm manually fetching/setting books on authors in my route. It certainly works, but seems a little hokey.

  model() {
    return Ember.RSVP.hash({
      authors: this.get('store').findAll('author'),
      books: this.get('store').findAll('book')
    });
  },

  afterModel(model) {
   model.authors.map((author) => {
     let books = model.books.filterBy('authorId', author.id);
     author.set('books', books);
   });
  }

I'm assuming this is probably the only sort of approach that'll work based on my API architecture, but I wanted to ask, is there some convention/serialization method/adapter magic I could potentially use to get what I want out of the box with Ember data?

https://ember-twiddle.com/67cbaeb149a68017e94ae07729bd3d74?openFiles=routes.application.js%2Ctemplates.components.author-books.hbs

Posts: 4

Participants: 2

Read full topic


Viewing all articles
Browse latest Browse all 4830

Trending Articles