Last active
August 29, 2015 14:17
-
-
Save Keeo/0d8d99a50edfdd120bf0 to your computer and use it in GitHub Desktop.
Ember data custom store function able to find entity by custom field not id only. Usefull for finding by secondary keys as slug or name.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// for ember-cli place in app/store.js | |
import Ember from 'ember'; | |
import DS from 'ember-data'; | |
export default DS.Store.extend({ | |
/** | |
* Acts as find(type, id) but can be used on any field. | |
* @param type | |
* @param field | |
* @param value | |
* @return {Promise} promise | |
*/ | |
findAsId: function (type, field, value) { | |
Ember.assert("You need to pass a type, field and value.", arguments.length === 3); | |
var entity = this.all(type).findBy(field, value); | |
if (Ember.isEmpty(entity)) { | |
var query = {}; | |
query[field] = value; | |
return this.find(type, query).then(function (array) { | |
Ember.assert('Must find only one object. Found:' + array.get('length'), array.get('length') === 1); | |
return array.get('firstObject'); | |
}); | |
} else { | |
return new Ember.RSVP.Promise(function(resolve){ | |
resolve(entity); | |
}); | |
} | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment