Skip to content

Instantly share code, notes, and snippets.

@honzabrecka
Created May 11, 2018 09:41
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 honzabrecka/0da7f2a8296455a82dab88f6839fc61b to your computer and use it in GitHub Desktop.
Save honzabrecka/0da7f2a8296455a82dab88f6839fc61b to your computer and use it in GitHub Desktop.
/* 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