Created
July 16, 2017 16:40
-
-
Save galvez/23ff6951724558c1d0e47a2d05009128 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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