Skip to content

Instantly share code, notes, and snippets.

@konsumer
Last active March 2, 2017 16:43
Show Gist options
  • Save konsumer/4aa4f65304cd5fb4e20c1c4b7a556da9 to your computer and use it in GitHub Desktop.
Save konsumer/4aa4f65304cd5fb4e20c1c4b7a556da9 to your computer and use it in GitHub Desktop.
Simple ES6 class for using fetch sort of like angular's $resource (to use in react, for example)
/**
* Generic model for interacting with REST object, similar to angular's $resource
*
* query([obj]) - GET /entries
* get(id) - GET /entries/:id
* save(obj) - POST/PUT (create/update) /entries /entries/:id
* remove(id) - DELETE /entries/:id
*
* on server-side, you can use angular-bridge for easy REST interface in mongoose/express
*/
import urlencode from 'urlencode'
// fetch with defaults geared towards JSON
export function http (url, optionsIn) {
const options = Object.assign({}, this.default, optionsIn)
return window.fetch.apply(url, options)
.then(options.onSuccess, options.onError)
}
http.default = {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
onSuccess: r => {
if (r.ok) return r.json()
return r.json().then(e => {
e.response = r
Promise.reject(e)
})
},
onError: e => e.json()
}
export default class Resource {
constructor (prefix) {
this.prefix = prefix
}
query (query) {
return query
? http(`${this.prefix}?${urlencode.stringify(query)}`, {method: 'GET'})
: http(this.prefix, {method: 'GET'})
}
get (id) {
return http(`${this.prefix}/${id}`, {method: 'GET'})
}
save (obj) {
const body = JSON.stringify(obj)
return obj.id
? http(`${this.prefix}/${obj.id}`, {method: 'PUT', body: body})
: http(`${this.prefix}`, {method: 'POST', body: body})
}
remove (id) {
return http(`${this.prefix}/${id}`, {method: 'DELETE'})
}
}
// alias
Resource.delete = Resource.remove
import Resource from './Resource'
const User = new Resource('/user')
// get all
User.query()
.then(response => console.log(response) )
// get some, by a query
User.query({verified: true})
.then(response => console.log(response) )
// get a single
User.get('507f1f77bcf86cd799439011')
.then(response => console.log(response))
// create
User.save({email: 'konsumer@jetboystudio.com', verified: false})
.then(response => console.log(response))
// update
User.save({id: '507f1f77bcf86cd799439011', email: 'konsumer@jetboystudio.com', verified: true})
.then(response => console.log(response))
// delete
User.delete('507f1f77bcf86cd799439011')
.then(response => console.log(response))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment