Skip to content

Instantly share code, notes, and snippets.

@ahx
Last active March 15, 2018 19:52
Show Gist options
  • Save ahx/6607308 to your computer and use it in GitHub Desktop.
Save ahx/6607308 to your computer and use it in GitHub Desktop.
A ember-model adapter for hoodie.js. Hoodie: http://hood.ie ember-model: https://github.com/ebryn/ember-model
// Usage:
// HoodieAdapter.create({type: "mystuff", url: "some/url"})
// "type" is required. "url" is optional.
var hoodie,
get = Ember.get,
Promise = Ember.RSVP.Promise;
function mustImplement(message) {
var fn = function() {
var className = this.constructor.toString();
throw new Error(message.replace('{{className}}', className));
};
fn.isUnimplemented = true;
return fn;
}
var HoodieAdapter = Ember.Adapter.extend({
init: function() {
if (!this.get('type')) {
throw new Error('You must provide a "type" option that is used as a namespace to store Objects: HoodieAdapter.create({type: "mystuff"}).');
}
hoodie = new Hoodie(this.get('url'));
this._super();
},
find: function(record, id) {
var klass = record.constructor;
return hoodie.store.find(this.get('type'), id).then(function(data) {
Ember.run(record, record.load, klass, data);
return record;
});
},
findQuery: mustImplement('{{className}} must implement findQuery'),
findMany: mustImplement('{{className}} must implement findMany'),
findAll: function(klass, records) {
return hoodie.store.findAll(this.get('type')).done(function(data) {
records.load(klass, data);
return records;
});
},
createRecord: function(record) {
var self = this;
return new Promise(function(resolve, reject) {
hoodie.store.add(self.get('type'), record.toJSON()).then(function(data){
record.load(data['id'], data);
record.didCreateRecord();
resolve(record);
}, reject);
});
},
saveRecord: function(record) {
var id = get(record, 'id'),
self = this;
return hoodie.store.update(this.get('type'), id, record.toJSON()).done(function(data){
record.didSaveRecord();
return record;
});
},
deleteRecord: function(record) {
var id = get(record, 'id'),
self = this;
return hoodie.store.remove(this.get('type'), id).then(function(data){
record.didDeleteRecord();
});
}
});
export default HoodieAdapter;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment