Skip to content

Instantly share code, notes, and snippets.

@galvez
Created July 16, 2017 16:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save galvez/23ff6951724558c1d0e47a2d05009128 to your computer and use it in GitHub Desktop.
Save galvez/23ff6951724558c1d0e47a2d05009128 to your computer and use it in GitHub Desktop.
import fetch from 'isomorphic-fetch'
import { ENV } from 'constants/env'
export const URL = (path, host, schema = 'http') => {
return `${schema}://${host}/${path}/`
}
export const GET = 'GET'
export const DELETE = 'DELETE'
export const HEAD = 'HEAD'
export const PATCH = 'PATCH'
export const POST = 'POST'
export const PUT = 'PUT'
export const OPTIONS = 'OPTIONS'
const fetchWith = (method, url, body, headers) => {
return fetch(url, {
method,
body,
headers
})
}
export function request (host, headers = {}, secure = true) {
return (path, method, params = {}, extraHeaders = {}) => fetchWith(
method,
URL(path, host, `http${secure ? 's' : ''}`),
params,
{ ...headers, ...extraHeaders }
)
}
export function makeClient (base, headers) {
const fetch = request(`${base}/v1`, headers, ENV === 'production')
return async function client (path, method, params) {
const response = await fetch(path, method, JSON.stringify(params))
const status = response.status
let data
try {
data = await response.json()
} catch (error) {
data = error
}
return { status, data }
}
}
export const defaultHeaders = {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment