Skip to content

Instantly share code, notes, and snippets.

@garth
Created September 13, 2013 08:15
Show Gist options
  • Save garth/6547991 to your computer and use it in GitHub Desktop.
Save garth/6547991 to your computer and use it in GitHub Desktop.
I had lots of problems getting ember data (1.0.0-beta.2) to work our back end services. After many hours of debugging I decided to write this hold us over until ember data stabilizes.
App.DataAccess = Ember.Object.create({
namespace: 'api',
cache: {},
getTypeName: function (type) {
return type.toString().match(/\w+$/);
},
isId: function (query) {
return typeof query === 'string' || typeof query == 'number';
},
buildUrl: function (type, query) {
var url = '/' + this.get('namespace') + '/';
if (this.isId(query)) {
url += this.getTypeName(type) + '/' + query;
}
else {
url += this.pluralize(this.getTypeName(type));
if (typeof query === 'object') {
var params = [];
for (var key in query) {
params.push(encodeURIComponent(key) + '=' + encodeURIComponent(query[key]));
}
if (params.length > 0) {
url += '?' + params.join('&');
}
}
}
return url;
},
// type is an ember class
// query is an id or hash where keys/values will be passed on the query string
// without query all objects are returned
find: function (type, query, skipCache) {
if (!skipCache) {
//check the cache
var cache = this.get('cache');
if (cache[type] && cache[type][query]) {
console.log('from cache');
return cache[type][query];
}
}
var url = this.buildUrl(type, query);
var self = this;
return $.getJSON(url).then(
function (response) {
console.log('from ' + url);
var result = self.serialize(type, response);
if (!self.isId(query)) {
// cache the query result
self.addToCache(type, query, result);
}
return result;
}
);
},
serialize: function (type, data) {
if (data instanceof Array) {
var items = Ember.A();
for (var i = 0; i < data.length; i++) {
items.pushObject(this.serialize(type, data[i]));
}
return items;
}
else {
if (this.serializers[type.name]) {
return this.serializers[type.name](data);
}
else {
var obj = type.create(data);
if (data.id) {
// cache the object
this.addToCache(type, data.id, obj);
}
return obj;
}
}
},
addToCache: function (type, key, item) {
var cache = this.get('cache');
if (!cache[type]) {
cache[type] = {};
}
cache[type][key] = item;
},
pluralize: function (name) {
var plurals = this.get('plurals');
return plurals[name] ? plurals[name] : name + 's';
},
// hash of pluras that break the "append s" default
plurals: {
person: "people",
},
// hash of custom serializers keyed by type name
serializers: {
}
});
App.Person = Ember.Object.extend({
firstName: null,
lastName: null
});
App.PersonRoute = Ember.Route.extend({
model: function (params) {
return App.DataAccess.find(App.Person, params.person_id);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment