Skip to content

Instantly share code, notes, and snippets.

@ezy
Created October 28, 2018 22:07
Show Gist options
  • Select an option

  • Save ezy/26a5e37003507825b43fdb90dd20a028 to your computer and use it in GitHub Desktop.

Select an option

Save ezy/26a5e37003507825b43fdb90dd20a028 to your computer and use it in GitHub Desktop.
Generic REST application.js CRUD adapter for `ember-cli-simple-store` with `ember-simple-auth`
import config from 'newseed/config/environment';
import { inject as service } from '@ember/service';
import RSVP from 'rsvp';
import EmberObject from '@ember/object';
import PromiseMixin from 'ember-promise/mixins/promise';
import DataAdapterMixin from 'ember-simple-auth/mixins/data-adapter-mixin';
var RESTAdapter = EmberObject.extend(DataAdapterMixin, {
simpleStore: service(),
session: service('session'),
serverEndpoint: `${config.apiHost}/${config.apiNameSpace}/`,
authorize(xhr) {
let { access_token } = this.get('session.data.authenticated');
xhr.setRequestHeader('Authorization', `Bearer ${access_token}`);
},
find(store) {
const simpleStore = this.get('simpleStore');
const serverEndpoint = this.get('serverEndpoint');
return PromiseMixin.xhr(`${serverEndpoint}/${store}/`, 'GET').then((response) => {
response.forEach(function(item) {
simpleStore.push(`${store}`, item);
});
return simpleStore.find(`${store}`);
});
},
findById(store, id) {
const simpleStore = this.get('simpleStore');
return simpleStore.find(`${store}`, id);
},
insert(store, item) {
const simpleStore = this.get('simpleStore');
const serverEndpoint = this.get('serverEndpoint');
let hash = { data: JSON.stringify(item) };
return new RSVP.Promise(function(resolve, reject) {
return PromiseMixin.xhr(`${serverEndpoint}/${store}/`, 'POST', hash).then(function(persisted) {
var inserted = simpleStore.push(`${item}`, persisted);
resolve(inserted);
}, function(err) {
reject(err);
});
});
},
update(store, item) {
const _id = item.get('id');
const serverEndpoint = this.get('serverEndpoint');
const hash = {
data: JSON.stringify(item)
};
const endpoint = `${serverEndpoint}/${store}/%@/`.fmt(_id);
return PromiseMixin.xhr(endpoint, 'PUT', hash);
},
remove(store, item) {
const simpleStore = this.get('simpleStore');
const serverEndpoint = this.get('serverEndpoint');
const _id = item.get('id');
const endpoint = `${serverEndpoint}/${store}/%@/`.fmt(_id);
return new RSVP.Promise(function(resolve, reject) {
return PromiseMixin.xhr(endpoint, 'DELETE').then(function(arg) {
simpleStore.remove(`${store}`, _id);
resolve(arg);
}, function(err) {
reject(err);
});
});
}
});
export default RESTAdapter;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment