http-client/readme.md
James Brumond 07138d4111
Some checks failed
Build and test / build-and-test (18.x) (push) Failing after 10s
Build and test / build-and-test (20.x) (push) Failing after 40s
migrate basic http client and response cache into library repo
2023-08-21 13:22:23 -07:00

71 lines
1.5 KiB
Markdown

Bare-minimum HTTP client library
Features:
- **Zero** dependencies
- Built-in response cache
---
## Install
```bash
# Update project npm config to refer to correct registry for the @js scope
echo '@js:registry=https://gitea.jbrumond.me/api/packages/js/npm/' >> ./.npmrc
npm install --save @js/http-client
# optional - additional supporting typescript definitions
npm install --save-dev @js/types
```
## Usage
```ts
import { create_http_client } from '@js/http-client';
const http = create_http_client({
// Default configuration:
logger: null, // (optional) expects a pino logger or compatible
https_only: false,
cache: {
// These settings are based on the recommendations in [RFC 9111], with the
// exception of not caching POST responses (because its not very commonly
// useful and is complicated) and with the addition of invalidating caches
// on successful PATCH requests (because they are fairly common use and
// are expected to modify the referenced resource)
//
// [RFC 9111]: https://www.rfc-editor.org/rfc/rfc9111.html
cacheable_methods: [ 'GET', 'HEAD' ],
cache_invalidating_methods: [ 'POST', 'PUT', 'PATCH', 'DELETE' ],
cacheable_status_codes: [
200, 203, 204, 206, 300, 301, 308, 404, 405, 410, 414, 501
],
},
});
const { status, headers, content } = await http.get('https://example.com', {
'accept': 'application/json'
});
if (status === 200) {
const json = JSON.parse(content);
console.log('received data', json);
}
```
## Building Locally (for development)
```bash
npm ci
npm run tsc
```