Last active
May 29, 2020 10:39
-
-
Save doasync/5d2e304624570f1345e594a765405468 to your computer and use it in GitHub Desktop.
Axios-like fetch
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
const queryString = (params) => { | |
const qs = String(new URLSearchParams(params)); | |
return qs ? `?${qs}` : ""; | |
}; | |
const joinBase = (url, baseUrl) => | |
`${baseUrl.replace(/\/$/, "")}/${url.replace(/^\/|\/$/, "")}/`; | |
const contentTypeJson = { "Content-Type": "application/json" }; | |
export const createRequest = (baseConfig) => (customConfig) => { | |
const config = { ...baseConfig, ...customConfig }; | |
const { baseUrl, url, data, params, fn, silent, ...init } = config; | |
const resource = `${joinBase(url, baseUrl)}${queryString(params)}`; | |
if (data) { | |
Object.assign(init, { | |
headers: { ...contentTypeJson, ...config.headers }, | |
body: JSON.stringify(data), | |
}); | |
} | |
const request = new Request(resource, init); | |
const handleRequestErrors = (response) => { | |
if (!response.ok) { | |
const error = Error(response.statusText); | |
Object.assign(error, { response, config, request }); | |
throw error; | |
} | |
return response; | |
}; | |
return fetch(request) | |
.then(!silent ? handleRequestErrors : (x) => x) | |
.then(async (response) => { | |
let jsonData; | |
try { | |
jsonData = await response.json(); | |
} catch (error) { | |
/* skip */ | |
} | |
return fn | |
? fn({ config, request, response, jsonData, resource, init, baseConfig }) | |
: jsonData; | |
}); | |
}; | |
export const request = createRequest(); |
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 { createRequest } from "./request"; | |
const request = createRequest({ | |
baseUrl: "https://example.com/api", | |
redirect: "error" | |
}); | |
const ENDPOINT = { | |
user: () => (id) => `user/${id}`, | |
confirm: () => 'confirm', | |
otherEndpoint: (params) => "blabla", | |
}; | |
export const getUser = (id) => request({ url: ENDPOINT.user(id) }); | |
export const confirm = (id) => request({ | |
url: ENDPOINT.confirm(), | |
data: { id }, | |
fn: ({ jsonData: user, config }) => config.data.id === user.id | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment