fetchmap
Non-throwing fetch wrapper
Getting started
npm i fetchmap
Description
This is a simple wrapper for standard fetch
function that catches all possible exceptions and returns a 'success or failure' wrapped value. It takes an object to map response.status
to (response: Response) => unknown
transform, standard fetch
arguments and a fetch
function itself. The last argument can be curried.
Example
import express from 'express'
express()
.get('/json', (_, res) => {
res.json({ some: 'data' })
})
.listen(5005)
import { fetchmap } from 'fetchmap'
const json_success = await fetchmap({ ok: 'json' }, 'https://localhost:5005/json')(fetch)
expect(json_success).toEqual({ tag: 'success', success: { some: 'data' } })
const json_success_only_200 = await fetchmap({ 200: 'json' }, 'https://localhost:5005/json')(fetch)
expect(json_success_only_200).toEqual({ tag: 'success', success: { some: 'data' } })
const invalid_url_failure_non_curried_form = await fetchmap({}, '1234', undefined, fetch)
expect(invalid_url_failure_non_curried_form).toEqual({
tag: 'failure',
failure: { clientError: new TypeError('Only absolute URLs are supported') }
})
const not_found_error_with_request_init = await fetchmap(
{ notOk: ({ status }: Response) => status },
'https://localhost:5005/invalid',
{ method: 'POST', credentials: 'include' }
)(fetch)
expect(not_found_error_with_request_init).toEqual({ tag: 'failure', failure: { serverError: 404 } })
Usage
See test or playground
Misc
ts-railway - compatible result library