1 |
|
2 | [![NPM downloads](https://img.shields.io/npm/dm/@bbc/http-transport.svg?style=flat)](https://npmjs.org/package/@bbc/http-transport)
|
3 | ![npm](https://img.shields.io/npm/v/@bbc/http-transport.svg)
|
4 | ![license](https://img.shields.io/badge/license-MIT-blue.svg)
|
5 | ![github-issues](https://img.shields.io/github/issues/bbc/http-transport.svg)
|
6 | ![stars](https://img.shields.io/github/stars/bbc/http-transport.svg)
|
7 | ![forks](https://img.shields.io/github/forks/bbc/http-transport.svg)
|
8 |
|
9 | # http-transport
|
10 |
|
11 | > A flexible, modular REST client built for ease-of-use and resilience
|
12 |
|
13 | ## Installation
|
14 |
|
15 | ```
|
16 | npm install @bbc/http-transport --save
|
17 | ```
|
18 |
|
19 | ## Usage
|
20 |
|
21 | ```js
|
22 | const url = 'http://example.com/';
|
23 | const client = require('@bbc/http-transport').createClient();
|
24 |
|
25 | const res = await client
|
26 | .get(url)
|
27 | .asResponse();
|
28 |
|
29 | if (res.statusCode === 200) {
|
30 | console.log(res.body);
|
31 | }
|
32 | ```
|
33 |
|
34 | ## Documentation
|
35 | For more examples and API details, see [API documentation](https://bbc.github.io/http-transport)
|
36 |
|
37 | ## TypeScript
|
38 | Types are included in this project, and they also work with plugins.
|
39 |
|
40 | Just pass the types that your plugin will add to `context` as a generic. This will be overlayed on top of any types added by previous plugins in the chain.
|
41 |
|
42 | E.g.
|
43 |
|
44 | ```ts
|
45 | const addSessionData: Plugin<{ session: { userId: string } } }> = (context, next) => {
|
46 | context.session = { userId: 'some-user' };
|
47 | };
|
48 |
|
49 | const res = await client
|
50 | .use(addSessionData)
|
51 | .use((context, next) => {
|
52 | if (context.session.userId === 'some-user') { // this would error if addSessionData middleware was missing
|
53 | // do something
|
54 | }
|
55 | })
|
56 | .use<{res: { random: number } }>((context, next) => {
|
57 | context.res.random = Math.random();
|
58 | })
|
59 | .get(url)
|
60 | .asResponse();
|
61 |
|
62 | console.log(res.random); // number
|
63 | ```
|
64 |
|
65 | ## Opting Out
|
66 | If you don't want to type your plugin, simply use `any` as the type. This is not recommended though as it means all plugins later in the chain will lose the types too, because they have no idea what changes were made.
|
67 |
|
68 | ```ts
|
69 | const myPlugin: Plugin<any> = (context, next) => {};
|
70 | ```
|
71 |
|
72 | ## Test
|
73 |
|
74 | ```
|
75 | npm test
|
76 | ```
|
77 |
|
78 | To generate a test coverage report:
|
79 |
|
80 | ```
|
81 | npm run coverage
|
82 | ```
|