1.13.0 • Published 10 months ago

@marianmeres/http-utils v1.13.0

Weekly downloads
-
License
MIT
Repository
github
Last release
10 months ago

@marianmeres/http-utils

A few opinionated sweet fetch helpers.

Example

import { HTTP_ERROR, HTTP_STATUS, createHttpApi } from '@marianmeres/http-utils';

// create api helper
const api = createHttpApi(
    // optional base url
    'https://api.example.com',
    // optional lazy evaluated default fetch params (can be overridden per call)
    async () => ({
        token: await getApiTokenFromDb() // example
    })

// EXAMPLE: assuming `/resource` returns json {"some":"data"}
const r = await api.get('/resource');
assert(r.some === 'data');

// EXAMPLE: assuming `/foo` returns 404 header and json {"message":"hey"}
// by default always throws
try {
    const r = await api.get('/foo');
} catch (e) {
    // see HTTP_ERROR for more
    assert(e instanceof HTTP_ERROR.NotFound);
    assert(e.toString() === 'HttpNotFoundError: Not Found');
    assert(e.status === HTTP_STATUS.ERROR_CLIENT.NOT_FOUND.CODE);
    assert(e.statusText === HTTP_STATUS.ERROR_CLIENT.NOT_FOUND.TEXT);
    // `body` is a custom prop containing the raw http response body text (JSON.parse-d if available)
    assert(e.body.message === 'hey');
    // `cause` is a standart Error prop, containing here some default debug info
    assert(err.cause.response.headers)
}

// EXAMPLE: assuming `/foo` returns 404 header and json {"message":"hey"}
// will not throw if we pass false flag
const r = await api.get('/foo', { assert: false });
assert(r.message === 'hey');

// EXAMPLE: assuming POST to `/resource` returns OK and json {"message":"created"}
// the provided token below will override the one from the `getApiTokenFromDb()` call above
const r = await api.post('/resource', { some: 'data' }, { token: 'my-api-token' });
assert(r.message === 'created');

// EXAMPLE: raw Response
const r = await api.get('/resource', { raw: true });
assert(r instanceof Response);

// EXAMPLE: access to response headers
let respHeaders = {};
const r = await api.get('/resource', null, respHeaders);
assert(Object.keys(respHeaders).length)

See HTTP_STATUS and HTTP_ERROR for more.

1.13.0

10 months ago

1.12.0

11 months ago

1.11.0

11 months ago

1.10.0

11 months ago

1.9.0

11 months ago

1.8.0

11 months ago

1.7.1

11 months ago

1.7.0

11 months ago

1.6.4

11 months ago

1.6.3

11 months ago

1.6.2

11 months ago

1.6.1

11 months ago

1.6.0

11 months ago

1.5.0

11 months ago

1.4.0

11 months ago

1.3.2

11 months ago

1.3.0

11 months ago

1.2.0

11 months ago

1.1.0

11 months ago

1.0.2

11 months ago

1.0.1

11 months ago