1 |
|
2 | [![NPM downloads](https://img.shields.io/npm/dm/@bbc/http-transport.svg?style=flat)](https://npmjs.org/package/@bbc/http-transport)
|
3 | [![Build Status](https://api.travis-ci.org/bbc/http-transport.svg)](https://travis-ci.org/bbc/http-transport)
|
4 | ![npm](https://img.shields.io/npm/v/@bbc/http-transport.svg)
|
5 | ![license](https://img.shields.io/badge/license-MIT-blue.svg)
|
6 | ![github-issues](https://img.shields.io/github/issues/bbc/http-transport.svg)
|
7 | ![stars](https://img.shields.io/github/stars/bbc/http-transport.svg)
|
8 | ![forks](https://img.shields.io/github/forks/bbc/http-transport.svg)
|
9 |
|
10 | # http-transport
|
11 |
|
12 | > A flexible, modular REST client built for ease-of-use and resilience
|
13 |
|
14 | ## Installation
|
15 |
|
16 | ```
|
17 | npm install @bbc/http-transport --save
|
18 | ```
|
19 |
|
20 | ## Usage
|
21 |
|
22 | ```js
|
23 | const url = 'http://example.com/';
|
24 | const client = require('@bbc/http-transport').createClient();
|
25 |
|
26 | const res = await client
|
27 | .get(url)
|
28 | .asResponse();
|
29 |
|
30 | if (res.statusCode === 200) {
|
31 | console.log(res.body);
|
32 | }
|
33 | ```
|
34 |
|
35 | ## Documentation
|
36 | For more examples and API details, see [API documentation](https://bbc.github.io/http-transport)
|
37 |
|
38 | ## TypeScript
|
39 | Types are included in this project, and they also work with plugins.
|
40 |
|
41 | 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.
|
42 |
|
43 | E.g.
|
44 |
|
45 | ```ts
|
46 | const addSessionData: Plugin<{ session: { userId: string } } }> = (context, next) => {
|
47 | context.session = { userId: 'some-user' };
|
48 | };
|
49 |
|
50 | const res = await client
|
51 | .use(addSessionData)
|
52 | .use((context, next) => {
|
53 | if (context.session.userId === 'some-user') { // this would error if addSessionData middleware was missing
|
54 | // do something
|
55 | }
|
56 | })
|
57 | .use<{res: { random: number } }>((context, next) => {
|
58 | context.res.random = Math.random();
|
59 | })
|
60 | .get(url)
|
61 | .asResponse();
|
62 |
|
63 | console.log(res.random); // number
|
64 | ```
|
65 |
|
66 | ## Opting Out
|
67 | 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.
|
68 |
|
69 | ```ts
|
70 | const myPlugin: Plugin<any> = (context, next) => {};
|
71 | ```
|
72 |
|
73 | ## Test
|
74 |
|
75 | ```
|
76 | npm test
|
77 | ```
|
78 |
|
79 | To generate a test coverage report:
|
80 |
|
81 | ```
|
82 | npm run coverage
|
83 | ```
|