@tramvai/module-http-client 1.15.1 → 1.25.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +206 -0
- package/README.md +4 -4
- package/package.json +10 -10
package/README.en.md
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
# @tramvai/module-http-client
|
|
2
|
+
|
|
3
|
+
The module provides the application with a factory of HTTP clients, a basic service for working with various APIs and a service for working with `papi`.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
You need to install `@tramvai/module-http-client`
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
yarn add @tramvai/module-http-client
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
And connect in the project
|
|
14
|
+
|
|
15
|
+
```tsx
|
|
16
|
+
import { createApp } from '@tramvai/core';
|
|
17
|
+
import { HttpClientModule } from '@tramvai/module-http-client';
|
|
18
|
+
|
|
19
|
+
createApp({
|
|
20
|
+
name: 'tincoin',
|
|
21
|
+
modules: [HttpClientModule],
|
|
22
|
+
});
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
## Features
|
|
26
|
+
|
|
27
|
+
The `http-client` module adds functionality to the application related to API requests. Available providers allow you to create new services to work with any API and create more specific services with preset settings for specific APIs.
|
|
28
|
+
|
|
29
|
+
The module implements interfaces from the library [@tramvai/http-client](references/libs/http-client.md) using a special library - adapter [@tramvai/tinkoff-request-http-client-adapter](references/libs/tinkoff-request-http-client-adapter.md), running on top of [@tinkoff/request](https://tinkoffcreditsystems.github.io/tinkoff-request/).
|
|
30
|
+
|
|
31
|
+
## Concepts
|
|
32
|
+
|
|
33
|
+
### HTTP client
|
|
34
|
+
|
|
35
|
+
HTTP client - implementation of the `HttpClient` interface, created via the `HTTP_CLIENT_FACTORY` token. HTTP client accepts general settings, some of which will be used as defult values for all requests. The HTTP client does not provide an opportunity to add additional methods for requests, and to perform side actions when the request is completed or failed.
|
|
36
|
+
|
|
37
|
+
### Services for working with API
|
|
38
|
+
|
|
39
|
+
The API service inherits from the `ApiService` class, which is exported from `@tramvai/http-client`. The API service takes an HTTP client in its constructor and uses it for requests. The API service implements all methods for requests from the `HttpClient` interface, but allows you to modify them. For example, you can replace the implementation of the `request` method by adding an error message to the `catch` request via an HTTP client - this logic will automatically work for all other methods - `get`, `put`, `post`, `delete`. In the API service, you can add custom methods for requests to certain API endpoints, and specify only the necessary parameters in them, and type responses.
|
|
40
|
+
|
|
41
|
+
Additional reasons to create API services - if you need to use several different HTTP clients to work with a specific API, or you need the ability to add a convenient abstraction on top of the basic methods for sending requests.
|
|
42
|
+
|
|
43
|
+
## Usage
|
|
44
|
+
|
|
45
|
+
### Create a new HTTP client
|
|
46
|
+
|
|
47
|
+
Each new HTTP client must directly or indirectly inherit `HTTP_CLIENT_FACTORY`.
|
|
48
|
+
|
|
49
|
+
New HTTP clients / API services should not be created with `scope: Scope.SINGLETON`, because each request is supplemented with default parameters specific to each user, for example - passing the `X-Real-Ip` header from the request to the application in all requests to the API.
|
|
50
|
+
|
|
51
|
+
#### Basic HTTP client
|
|
52
|
+
|
|
53
|
+
The `HTTP_CLIENT_FACTORY` token - provides a factory for creating new HTTP clients. The options are preinstalled with a logger and a cache factory.
|
|
54
|
+
|
|
55
|
+
##### Peculiarities
|
|
56
|
+
|
|
57
|
+
- For all requests to the API, headers are added from the list returned by the `API_CLIENT_PASS_HEADERS` token, and `X-Real-Ip` from the current request to the application
|
|
58
|
+
|
|
59
|
+
**Token interface:**
|
|
60
|
+
|
|
61
|
+
```tsx
|
|
62
|
+
type HTTP_CLIENT_FACTORY = (options: HttpClientFactoryOptions) => HttpClient;
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
**Token use:**
|
|
66
|
+
|
|
67
|
+
```tsx
|
|
68
|
+
import { Scope, provide } from '@tramvai/core';
|
|
69
|
+
import { ENV_MANAGER_TOKEN } from '@tramvai/tokens-common';
|
|
70
|
+
import { HTTP_CLIENT_FACTORY } from '@tramvai/tokens-http-client';
|
|
71
|
+
|
|
72
|
+
const provider = provide({
|
|
73
|
+
provide: 'WHATEVER_API_HTTP_CLIENT',
|
|
74
|
+
useFactory: ({
|
|
75
|
+
factory,
|
|
76
|
+
envManager,
|
|
77
|
+
}: {
|
|
78
|
+
factory: typeof HTTP_CLIENT_FACTORY;
|
|
79
|
+
envManager: typeof ENV_MANAGER_TOKEN;
|
|
80
|
+
}) => {
|
|
81
|
+
return factory({
|
|
82
|
+
name: 'whatever-api',
|
|
83
|
+
baseUrl: envManager.get('WHATEVER_API'),
|
|
84
|
+
});
|
|
85
|
+
},
|
|
86
|
+
deps: {
|
|
87
|
+
factory: HTTP_CLIENT_FACTORY,
|
|
88
|
+
envManager: ENV_MANAGER_TOKEN,
|
|
89
|
+
},
|
|
90
|
+
});
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
### Using existing HTTP clients
|
|
94
|
+
|
|
95
|
+
Most HTTP clients implement additional logic for requests, and inherit from `ApiService`. Thus, each service has methods `get`, `post`, `put`, `delete` and `request`, but there may be specific methods.
|
|
96
|
+
|
|
97
|
+
#### Common HTTP client
|
|
98
|
+
|
|
99
|
+
The `HTTP_CLIENT` token provides a basic client for sending requests to any URLs, request caching is disabled.
|
|
100
|
+
|
|
101
|
+
**Token use:**
|
|
102
|
+
|
|
103
|
+
```tsx
|
|
104
|
+
import { createAction } from '@tramvai/core';
|
|
105
|
+
import { HTTP_CLIENT } from '@tramvai/tokens-http-client';
|
|
106
|
+
|
|
107
|
+
export const fetchAction = createAction({
|
|
108
|
+
name: 'fetch',
|
|
109
|
+
fn: async (_, __, { httpClient }) => {
|
|
110
|
+
const { payload, headers, status } = await httpClient.get(
|
|
111
|
+
'https://www.domain.com/api/endpoint'
|
|
112
|
+
);
|
|
113
|
+
return payload;
|
|
114
|
+
},
|
|
115
|
+
deps: {
|
|
116
|
+
httpClient: HTTP_CLIENT,
|
|
117
|
+
},
|
|
118
|
+
});
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
### Adding custom data to requests
|
|
122
|
+
|
|
123
|
+
Let's consider a case using the abstract service `WHATEVER_API_SERVICE` as an example. Let's say we want to add an `X-Real-Ip` header to every request:
|
|
124
|
+
|
|
125
|
+
```tsx
|
|
126
|
+
import { provide } from '@tramvai/core';
|
|
127
|
+
import { HttpClientRequest, HttpClient } from '@tramvai/http-client';
|
|
128
|
+
import { REQUEST_MANAGER_TOKEN } from '@tramvai/tokens-common';
|
|
129
|
+
|
|
130
|
+
const provider = provide({
|
|
131
|
+
provide: 'WHATEVER_API_SERVICE',
|
|
132
|
+
useFactory: ({
|
|
133
|
+
factory,
|
|
134
|
+
requestManager,
|
|
135
|
+
envManager,
|
|
136
|
+
}: {
|
|
137
|
+
factory: typeof HTTP_CLIENT_FACTORY;
|
|
138
|
+
requestManager: typeof REQUEST_MANAGER_TOKEN;
|
|
139
|
+
envManager: typeof ENV_MANAGER_TOKEN;
|
|
140
|
+
}) => {
|
|
141
|
+
return factory({
|
|
142
|
+
name: 'whatever-api',
|
|
143
|
+
baseUrl: envManager.get('WHATEVER_API'),
|
|
144
|
+
modifyRequest: (request: HttpClientRequest) => {
|
|
145
|
+
return {
|
|
146
|
+
...request,
|
|
147
|
+
headers: {
|
|
148
|
+
...request.headers,
|
|
149
|
+
'X-real-ip': requestManager.getClientIp(),
|
|
150
|
+
},
|
|
151
|
+
};
|
|
152
|
+
},
|
|
153
|
+
});
|
|
154
|
+
},
|
|
155
|
+
deps: {
|
|
156
|
+
factory: HTTP_CLIENT_FACTORY,
|
|
157
|
+
requestManager: REQUEST_MANAGER_TOKEN,
|
|
158
|
+
envManager: ENV_MANAGER_TOKEN,
|
|
159
|
+
},
|
|
160
|
+
});
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
## How to
|
|
164
|
+
|
|
165
|
+
### How to disable HTTP request caching?
|
|
166
|
+
|
|
167
|
+
To disable caching for all HTTP clients, pass the env variable `HTTP_CLIENT_CACHE_DISABLED: true` to the application
|
|
168
|
+
|
|
169
|
+
### Testing
|
|
170
|
+
|
|
171
|
+
#### Testing your api clients
|
|
172
|
+
|
|
173
|
+
If you have a module or providers that define api-clients, then it will be convenient to use special utilities in order to test them separately
|
|
174
|
+
|
|
175
|
+
```ts
|
|
176
|
+
import { testApi } from '@tramvai/module-http-client/tests';
|
|
177
|
+
import { CustomModule } from './module';
|
|
178
|
+
|
|
179
|
+
describe('testApi', () => {
|
|
180
|
+
it('test', async () => {
|
|
181
|
+
const { di, fetchMock, mockJsonResponse } = testApi({
|
|
182
|
+
modules: [CustomModule],
|
|
183
|
+
env: {
|
|
184
|
+
TEST_API: 'testApi',
|
|
185
|
+
},
|
|
186
|
+
});
|
|
187
|
+
const httpClient: typeof HTTP_CLIENT = di.get('CUSTOM_HTTP_CLIENT') as any;
|
|
188
|
+
|
|
189
|
+
mockJsonResponse({ a: 'aaa' });
|
|
190
|
+
|
|
191
|
+
const { payload } = await httpClient.get('test');
|
|
192
|
+
|
|
193
|
+
expect(payload).toEqual({ a: 'aaa' });
|
|
194
|
+
expect(fetchMock).toHaveBeenCalledWith('http://testApi/test', expect.anything());
|
|
195
|
+
});
|
|
196
|
+
});
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
## Exported tokens
|
|
200
|
+
|
|
201
|
+
[link](references/tokens/http-client-tokens.md)
|
|
202
|
+
|
|
203
|
+
## Environment Variables
|
|
204
|
+
|
|
205
|
+
- `HTTP_CLIENT_CACHE_DISABLED` - disable caching for all HTTP clients
|
|
206
|
+
- `HTTP_CLIENT_CIRCUIT_BREAKER_DISABLED` - disable plugin https://tinkoffcreditsystems.github.io/tinkoff-request/docs/plugins/circuit-breaker.html
|
package/README.md
CHANGED
|
@@ -38,12 +38,16 @@ HTTP клиент - реализация интерфейса `HttpClient`, со
|
|
|
38
38
|
|
|
39
39
|
API сервис - наследник класса `ApiService`, который экспортируется из `@tramvai/http-client`. API сервис принимает HTTP клиент в конструкторе, и использует его для запросов. API сервис реализует все методы для запросов из интерфейса `HttpClient`, но позволяет модифицировать их. Например, можно заменить реализацию метода `request`, добавив на `catch` запроса через HTTP клиент показ сообщения об ошибке - эта логика автоматически будет срабатывать для всех остальных методов - `get`, `put`, `post`, `delete`. В API сервис можно добавить кастомные методы для запросов к определенным API эндпоинтам, и указывать в них только нужные параметры, и типизировать ответы.
|
|
40
40
|
|
|
41
|
+
Дополнительные причины создавать API сервисы - если для работы с конкретным API требуется использовать несколько разных HTTP клиентов, либо нужна возможность добавить удобную абстракцию поверх базовых методов для отправки запросов.
|
|
42
|
+
|
|
41
43
|
## Использование
|
|
42
44
|
|
|
43
45
|
### Создание нового HTTP клиента
|
|
44
46
|
|
|
45
47
|
Каждый новый HTTP клиент должен быть прямым или косвенным наследником `HTTP_CLIENT_FACTORY`.
|
|
46
48
|
|
|
49
|
+
Новые HTTP клиенты / API сервисы не должны создаваться со `scope: Scope.SINGLETON`, т.к. в каждый запрос добавляются параметры по умолчанию, спецфичные для каждого пользователя, например - передача заголовка `X-Real-Ip` из запроса в приложение во все запросы к API.
|
|
50
|
+
|
|
47
51
|
#### Базовый HTTP клиент
|
|
48
52
|
|
|
49
53
|
Токен `HTTP_CLIENT_FACTORY` - предоставляет фабрику для создания новых HTTP клиентов. В опциях предустановленны логгер и фабрика кэшей.
|
|
@@ -90,10 +94,6 @@ const provider = provide({
|
|
|
90
94
|
|
|
91
95
|
Большинство HTTP клиентов реализует дополнительную логику для запросов, и наследуется от `ApiService`. Таким образом, у каждого сервиса есть методы `get`, `post`, `put`, `delete` и `request`, но могут быть и специфичные методы.
|
|
92
96
|
|
|
93
|
-
Новые HTTP клиенты / API сервисы не должны создаваться со `scope: Scope.SINGLETON`, т.к. в каждый запрос добавляются параметры по умолчанию, спецфичные для каждого пользователя, например - передача заголовка `X-Real-Ip` из запроса в приложение во все запросы к API.
|
|
94
|
-
|
|
95
|
-
Дополнительные причины создавать API сервисы - если для работы с конкретным API требуется использовать несколько разных HTTP клиентов, либо нужна возможность добавить удобную абстракцию поверх базовых методов для отправки запросов.
|
|
96
|
-
|
|
97
97
|
#### Универсальный HTTP клиент
|
|
98
98
|
|
|
99
99
|
Токен `HTTP_CLIENT` предоставляет базовый клиент для отправки запросов на любые урлы, кэширование запросов отключено.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tramvai/module-http-client",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.25.0",
|
|
4
4
|
"initialVersion": "0.58.99",
|
|
5
5
|
"description": "",
|
|
6
6
|
"main": "lib/index.js",
|
|
@@ -25,21 +25,21 @@
|
|
|
25
25
|
},
|
|
26
26
|
"dependencies": {
|
|
27
27
|
"@tramvai/http-client": "0.1.21",
|
|
28
|
-
"@tramvai/tinkoff-request-http-client-adapter": "0.8.
|
|
29
|
-
"@tramvai/tokens-http-client": "1.
|
|
30
|
-
"@tramvai/tokens-common": "1.
|
|
31
|
-
"@tramvai/tokens-server": "1.
|
|
28
|
+
"@tramvai/tinkoff-request-http-client-adapter": "0.8.139",
|
|
29
|
+
"@tramvai/tokens-http-client": "1.25.0",
|
|
30
|
+
"@tramvai/tokens-common": "1.25.0",
|
|
31
|
+
"@tramvai/tokens-server": "1.25.0"
|
|
32
32
|
},
|
|
33
33
|
"devDependencies": {
|
|
34
34
|
"@tinkoff/request-core": "^0.8.9"
|
|
35
35
|
},
|
|
36
36
|
"peerDependencies": {
|
|
37
37
|
"@tinkoff/utils": "^2.1.2",
|
|
38
|
-
"@tramvai/core": "1.
|
|
39
|
-
"@tramvai/module-common": "1.
|
|
40
|
-
"@tramvai/papi": "1.
|
|
41
|
-
"@tramvai/test-helpers": "1.
|
|
42
|
-
"@tramvai/test-mocks": "1.
|
|
38
|
+
"@tramvai/core": "1.25.0",
|
|
39
|
+
"@tramvai/module-common": "1.25.0",
|
|
40
|
+
"@tramvai/papi": "1.25.0",
|
|
41
|
+
"@tramvai/test-helpers": "1.25.0",
|
|
42
|
+
"@tramvai/test-mocks": "1.25.0",
|
|
43
43
|
"@tinkoff/dippy": "0.7.35",
|
|
44
44
|
"node-fetch": "^2.6.1",
|
|
45
45
|
"tslib": "^2.0.3"
|