Created
May 11, 2018 09:41
-
-
Save honzabrecka/0da7f2a8296455a82dab88f6839fc61b to your computer and use it in GitHub Desktop.
This file contains 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
/* eslint-env browser */ | |
import fetch from 'isomorphic-fetch' | |
import { composableFetch, pipeP, tryCatchP } from 'composable-fetch' | |
export const handleFetchError = async (error) => { | |
const { res } = error | |
const genericError = new Error('Fetch error') | |
genericError.res = res | |
genericError.data = { success: false, message: 'An error occured.' } | |
try { | |
await composableFetch.decodeResponse(res) | |
if (typeof res.data === 'object' && res.data.message) | |
genericError.data = res.data | |
} catch (_) { | |
// | |
} | |
throw genericError | |
} | |
export const genericFetch = pipeP( | |
(req) => { | |
req.credentials = 'same-origin' | |
return req | |
}, | |
composableFetch.fetch1(fetch), | |
composableFetch.withSafe204(), | |
composableFetch.checkStatus, | |
) | |
const JSONReq = pipeP( | |
composableFetch.withHeader('Content-Type', 'application/json'), | |
composableFetch.withHeader('Accept', 'application/json'), | |
composableFetch.withEncodedBody(JSON.stringify), | |
) | |
const JSONRes = composableFetch.decodeJSONResponse | |
export const fetchJSONRaw = tryCatchP( | |
pipeP(JSONReq, genericFetch, JSONRes), | |
handleFetchError, | |
) | |
export const fetchJSON = pipeP( | |
fetchJSONRaw, | |
({ data }) => data, | |
// ({ payload }) => payload, | |
// TODO: If response doesn't have a `payload` property, it fails | |
// for example just message response in removeBooking: | |
// { | |
// success: true, | |
// message: 'Your booking has been removed', | |
// } | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment