Skip to content

Instantly share code, notes, and snippets.

@jdcauley jdcauley/fletch.js
Created Mar 23, 2018

Embed
What would you like to do?
yes no?
class Fletch {
constructor(props) {
this.defaults = {}
if (props.root) {
this.defaults.root = props.root
}
this.send = this.send.bind(this)
this.post = this.post.bind(this)
this.get = this.get.bind(this)
this.put = this.put.bind(this)
}
send(uri, config) {
let url = uri
console.log(this.defaults)
if (this.defaults && this.defaults.root) {
url = `${this.defaults.root}${uri}`
}
console.log(url)
const fetchConfig = config
if (!fetchConfig.headers) {
const headers = new Headers()
headers.append('Content-Type', 'application/json')
headers.append('Accept', 'application/json')
fetchConfig.headers = headers
}
return fetch(url, fetchConfig)
.then(response => response.json()
.then((data) => {
if (!response.ok) {
return Promise.reject(data)
}
return data
}))
.catch(err => Promise.reject(err))
}
get (uri, params = '') {
const config = {
method: 'GET',
}
return this.send(uri, config)
}
post (uri, params) {
const config = {
method: 'POST',
body: JSON.stringify(params),
}
return this.send(uri, config)
}
put (uri, params) {
const config = {
method: 'PUT',
body: JSON.stringify(params),
}
return this.send(uri, config)
}
delete (uri, params) {
const config = {
method: 'DELETE',
body: JSON.stringify(params),
}
return this.send(uri, config)
}
}
export default Fletch
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.