// Mixin RESTful sync behaviors to Reflux stores. Calls the .completed or .failed // action when the promise is fufilled. import sync from './sync'; export default (urlRoot, Actions) => { const getUrl = (id) => { let base = typeof urlRoot === 'function' ? urlRoot() : urlRoot; return id ? `${base}/${id}` : base; } return { // Returns a single model by id, or all models if no id passed. fetch(id, params) { let method = 'GET'; let url = getUrl(id); sync(url, {method, body: params}) .then(Actions.fetch.completed) .catch(Actions.fetch.failed); }, // Persists a single model to the server. Creates the model if the id doesn't // exist, or updates the record if it does. save(id, data) { let method = id ? 'PUT' : 'POST'; let url = getUrl(id); sync(url, {method, body: data}) .then(Actions.save.completed) .catch(Actions.save.failed); }, // Deletes a single model by id (required). delete(id) { if (!id) throw new Error('need an id to delete'); let method = 'DELETE' let url = getUrl(id); sync(url, {method}) .then(Actions.delete.completed.bind(this, id)) .catch(Actions.delete.failed.bind(this, id)); } }; };