generated from templates/typescript-library
71 lines
1.5 KiB
Markdown
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
|
|
```
|
|
|
|
|
|
|