jeudi 28 juillet 2016

Ember Data; Custom Adapter with hasMany relationship

I have following models

// models/user.js
export default Model.extend({
  name: attr(),
  contacts: hasMany('contact')
});

// models/contact.js
export default Model.extend({
  name: attr(),
  phoneNumber: attr(),
  user: belongsTo('user')
});

Unfortunately, I'm working with highly non-standard API layer that has something like following signatures

endpoint?method=getUsers 
  -> returns list of users

endpoint?method=getContacts&args="{user_id=1}" 
  -> returns list of contacts for user with id=1. (args would be url encoded)

basically I have to write a lot of custom adapters. I wrote an adapter for user and was able to get the list of users.

// adapters/user.js
export default Adapter.extend({
  findAll() {
    return // call getUsers and return the result here
  }
}

But I can't figure out how to get the contacts for the users. I can get all the users by doing following.

// in some route
model() {
  return this.get('store').findAll('user');
}

But I cannot figure out to fetch all the contacts for the users I tried following:

// in some route
model() {
  return this.get('store').findAll('user').then(users => {
    users.forEach(user => {
      user.get('contacts');
    }
  }
}

user.get('contacts') just returns an empty record.

What's the way I can the contacts of the user? I wrote a custom adapter for contact but Ember doesn't call it either.




Aucun commentaire:

Enregistrer un commentaire