@equinor/fusion-framework-module-http 5.2.3 → 6.0.1

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.
Files changed (65) hide show
  1. package/CHANGELOG.md +162 -0
  2. package/README.md +759 -36
  3. package/dist/esm/configurator.js +10 -1
  4. package/dist/esm/configurator.js.map +1 -1
  5. package/dist/esm/errors.js +18 -0
  6. package/dist/esm/errors.js.map +1 -1
  7. package/dist/esm/index.js +4 -0
  8. package/dist/esm/index.js.map +1 -1
  9. package/dist/esm/lib/client/client-msal.js +35 -0
  10. package/dist/esm/lib/client/client-msal.js.map +1 -1
  11. package/dist/esm/lib/client/client.js +153 -6
  12. package/dist/esm/lib/client/client.js.map +1 -1
  13. package/dist/esm/lib/operators/http-request-handler.js +16 -0
  14. package/dist/esm/lib/operators/http-request-handler.js.map +1 -1
  15. package/dist/esm/lib/operators/http-response-handler.js +6 -0
  16. package/dist/esm/lib/operators/http-response-handler.js.map +1 -1
  17. package/dist/esm/lib/operators/process-operators.js +49 -1
  18. package/dist/esm/lib/operators/process-operators.js.map +1 -1
  19. package/dist/esm/lib/operators/request-operator-header.js +7 -0
  20. package/dist/esm/lib/operators/request-operator-header.js.map +1 -1
  21. package/dist/esm/lib/selectors/blob-selector.js +28 -3
  22. package/dist/esm/lib/selectors/blob-selector.js.map +1 -1
  23. package/dist/esm/lib/selectors/json-selector.js +24 -0
  24. package/dist/esm/lib/selectors/json-selector.js.map +1 -1
  25. package/dist/esm/module.js +40 -0
  26. package/dist/esm/module.js.map +1 -1
  27. package/dist/esm/provider.js +65 -6
  28. package/dist/esm/provider.js.map +1 -1
  29. package/dist/esm/version.js +2 -1
  30. package/dist/esm/version.js.map +1 -1
  31. package/dist/tsconfig.tsbuildinfo +1 -1
  32. package/dist/types/configurator.d.ts +76 -0
  33. package/dist/types/errors.d.ts +18 -0
  34. package/dist/types/index.d.ts +4 -0
  35. package/dist/types/lib/client/client-msal.d.ts +43 -0
  36. package/dist/types/lib/client/client.d.ts +147 -3
  37. package/dist/types/lib/client/types.d.ts +156 -5
  38. package/dist/types/lib/operators/http-request-handler.d.ts +16 -0
  39. package/dist/types/lib/operators/http-response-handler.d.ts +6 -0
  40. package/dist/types/lib/operators/process-operators.d.ts +44 -0
  41. package/dist/types/lib/operators/request-operator-header.d.ts +7 -0
  42. package/dist/types/lib/operators/types.d.ts +57 -0
  43. package/dist/types/lib/selectors/blob-selector.d.ts +9 -1
  44. package/dist/types/lib/selectors/index.d.ts +1 -0
  45. package/dist/types/lib/selectors/json-selector.d.ts +16 -1
  46. package/dist/types/module.d.ts +35 -0
  47. package/dist/types/provider.d.ts +77 -0
  48. package/dist/types/version.d.ts +1 -1
  49. package/package.json +5 -5
  50. package/src/configurator.ts +38 -1
  51. package/src/errors.ts +11 -1
  52. package/src/lib/client/client-msal.ts +50 -5
  53. package/src/lib/client/client.ts +161 -12
  54. package/src/lib/client/types.ts +149 -71
  55. package/src/lib/operators/http-request-handler.ts +12 -4
  56. package/src/lib/operators/http-response-handler.ts +6 -0
  57. package/src/lib/operators/process-operators.ts +6 -1
  58. package/src/lib/operators/request-operator-header.ts +7 -0
  59. package/src/lib/operators/types.ts +22 -4
  60. package/src/lib/selectors/blob-selector.ts +26 -4
  61. package/src/lib/selectors/index.ts +2 -0
  62. package/src/lib/selectors/json-selector.ts +29 -9
  63. package/src/module.ts +55 -2
  64. package/src/provider.ts +76 -2
  65. package/src/version.ts +1 -1
package/README.md CHANGED
@@ -1,57 +1,780 @@
1
- ## Configure
1
+ # Fusion Framework Http Module
2
2
 
3
- Module for configuring and providing http clients
3
+ > __The Fusion Framework HTTP Module provides a streamlined and powerful HTTP client for making requests to APIs.__
4
+ >
5
+ > The module supports both asynchronous (Promise-based) and observable (RxJS-based) execution methods, allowing you to choose the approach that best suits your use case.
6
+ >
7
+ > It also offers advanced features, such as **MSAL** (Microsoft Authentication Library) integration, request and response operators, and response selectors, to enhance the functionality and flexibility of HTTP communication.
8
+
9
+ Whether you're building a simple application or a complex portal, the Fusion Framework HTTP Module equips you with the essential tools to handle HTTP requests efficiently and effectively. With its rich feature set and intuitive API, the module simplifies the process of working with HTTP clients, enabling you to focus on building robust and scalable applications.
10
+
11
+ **Key Features:**
12
+ - Streamlined API for easy configuration and operation of HTTP clients
13
+ - Integrated MSAL (Microsoft Authentication Library) support for robust authentication
14
+ - Unified management system for HTTP client configurations
15
+ - Factory method for client creation, ensuring optimal state management
16
+ - Capabilities for intercepting and modifying requests and responses
17
+ - Familiar syntax inspired by the [Web's Fetch API](https://developer.mozilla.org/en-US/docs/Web/HTTP)
18
+
19
+ ## Package
20
+
21
+ | Namespace | Description |
22
+ |-----------|-------------|
23
+ | `@equinor/fusion-framework-module-http` | http module
24
+ | `@equinor/fusion-framework-module-http/client` | http clients
25
+ | `@equinor/fusion-framework-module-http/selectors` | http selectors
26
+ | `@equinor/fusion-framework-module-http/operators` | http client operators
27
+ | `@equinor/fusion-framework-module-http/errors` | http client errors
28
+
29
+ ## Usage
30
+ Working with Fusion Framework, HTTP clients are defined during the configuration phase. The configuration is called by the Framework during initialization, ensuring that the HTTP clients are ready to be used. This approach allows for centralized and optimized client configuration, promoting consistency, performance, and security in HTTP communication within the Fusion Framework ecosystem.
31
+
32
+ see [Configuring HTTP Clients](#configuring-http-clients) for more information.
4
33
 
5
- ### Simple
6
34
  ```ts
7
- const configure = (config) => {
8
- config.http.configureClient(
9
- 'bar',
10
- 'https://somewhere-test.com'
11
- );
35
+ /**
36
+ * Example: Configuring an HTTP client with MSAL authentication in Fusion Framework
37
+ * This configuration is performed during the initialization phase of the app.
38
+ */
39
+ const configure = (configurator: IModulesConfigurator) => {
40
+ /**
41
+ * Configure an HTTP client named 'msalClient'
42
+ * This client is set up to communicate with 'https://api.example.com'
43
+ * and utilizes MSAL for authentication, specifying a default scope.
44
+ */
45
+ configurator.http.configureClient('msalClient', {
46
+ baseUri: 'https://api.example.com',
47
+ defaultScopes: ['api://example-api/.default'], // MSAL scopes
48
+ });
49
+
50
+ // Additional configuration can be added here
12
51
  }
52
+
53
+ // Note: This is a basic setup. For more advanced configurations, please refer to the documentation.
13
54
  ```
14
55
 
15
- ### Standard
56
+ When the application is initialized, the configuration is called, and the HTTP client becomes ready to be used.
57
+
58
+ see [Working with HTTP clients](#working-with-http-clients) for more information.
59
+
16
60
  ```ts
17
- const configure = (config) => {
18
- config.http.configureClient(
19
- 'bar',
20
- {
21
- baseUri: 'https://foo.bar',
22
- defaultScopes: ['foobar/.default']
23
- }
24
- );
61
+ /**
62
+ * Example: Using an HTTP client in Fusion Framework
63
+ * This code is executed after the app configuration has been initialized.
64
+ */
65
+ const client = modules.http.createClient('myClient');
66
+
67
+ /** Make a request using the client */
68
+ client.json('/some-endpoint')
69
+ .then(data => console.log(data))
70
+ .catch(error => console.error('Error:', error));
71
+ ```
72
+
73
+ ## Concepts
74
+
75
+ ### Pure fetch
76
+
77
+ The HTTP module extends the native `fetch` API, providing a streamlined experience for making HTTP requests. It adds features and capabilities to simplify common tasks and ensure compatibility with existing code and libraries.
78
+
79
+ ### Observable
80
+
81
+ The HTTP module uses RxJS observables for handling HTTP requests and responses. Observables provide a flexible and powerful way to work with asynchronous data streams. They allow you to process and transform data in a declarative and composable manner. Unsubscribing from an observable automatically aborts the corresponding HTTP request, preventing unnecessary network traffic and ensuring efficient request management.
82
+
83
+ ### Defining Clients Upfront
84
+
85
+ In the Fusion Framework, HTTP clients are configured during initialization to ensure they are ready for use. This promotes centralized configuration, optimized performance, and enhances consistency, security, and modularity in HTTP communication.
86
+
87
+ ### Client factory
88
+ The HTTP module provides a client factory method for creating HTTP clients. This method allows you to specify the client's name and retrieve a configured instance. Using the client factory ensures clean and predictable client instances without any mutations from previous requests. This promotes a reliable state for each client, avoiding unexpected behavior caused by shared state.
89
+
90
+ ### Process operators
91
+
92
+ Process operators are functions that can be added to the HTTP client to customize its behavior and add additional functionality to the request/response lifecycle. They allow you to intercept and modify requests and responses, add custom headers, log data, validate responses, and more. By using process operators, you can extend the functionality of the HTTP client to meet your application's specific requirements.
93
+
94
+ ### Request execution
95
+
96
+ When executing HTTP requests _(1)_, the internal fetch method will create an `Observable` _(2)_ from the provided the request options. The stream will then process the request handlers _(3 - 5)_ before emitting the request to the HttpClient request `Subject` _(6)_.
97
+
98
+ Then a native `fetch` call is made to the HTTP service _(7)_. If the request is successful _(17)_, the response is processed by the response handlers _(18 - 20)_ before being emitted to the HttpClient response `Subject` _(21)_. The response is then processed by the response selector _(22)_ before being emitted to the user (_23_).
99
+
100
+ In case of an error _(17)_, the error is emitted to the user _(18)_.
101
+
102
+ If the user calls abort on the client _(8)_, or triggers provided `AbortSignal` in call args, the observable will abort the request _(10)_. `fetch` will throw an abort error _(11)_, which is emitted to the user _(12)_.
103
+
104
+ If the user unsubscribes from the observable _(13)_ or trigger provided `AbortSignal` in call args, the request is aborted _(14)_.
105
+
106
+
107
+ > [!NOTE]
108
+ > - When an error is emitted, the observable will complete.
109
+ > - Observables only emit errors if they are subscribed to.
110
+ > - fetch observables are cold, meaning they will close when request is completed or aborted.
111
+
112
+ > [!IMPORTANT]
113
+ > HttpClient stream functions will not execute until subscribed to.
114
+
115
+ ```mermaid
116
+ sequenceDiagram
117
+ autonumber
118
+ actor User
119
+ participant Client
120
+
121
+ User->>Client: calls fetch method
122
+ create participant Observable
123
+ Client->>+Observable: create observable
124
+ Observable->>+Client: prepare request
125
+ loop
126
+ Client->>Client: process request handlers
127
+ end
128
+ Client-->>-Observable: request object
129
+ Observable-->>Client: emit request
130
+ create participant HTTPService as Http Service
131
+ Observable->>+HTTPService: fetch
132
+ break when aborted
133
+ User->>Client: abort requests
134
+ Client->>Observable: close observable
135
+ Observable->>HTTPService: abort request
136
+ HTTPService-->>Observable: Abort error
137
+ Observable--xUser: emit error
138
+ end
139
+ break when unsubscribe
140
+ User--xObservable: unsubscribe
141
+ Observable->>HTTPService: abort request
142
+ end
143
+ alt is request error
144
+ HTTPService-->>Observable: error
145
+ Observable--xUser: emit error
146
+ end
147
+ HTTPService-->>-Observable: response
148
+ Observable-->>+Client: prepare response
149
+ loop
150
+ Client->>Client: process response handlers
151
+ end
152
+ Client-->>-Observable: response object
153
+ Observable-->>Client: emit response
154
+ opt
155
+ Observable->>Observable: apply response selector
156
+ end
157
+ Observable--x-User: emit result
158
+ ```
159
+
160
+ ## Configuring HTTP Clients
161
+
162
+ Configuring HTTP clients before the application renders is crucial for several reasons:
163
+
164
+ 1. **Centralized Configuration**: By configuring clients upfront, we establish a single source of truth for all HTTP client settings. This centralization simplifies the management and maintenance of client configurations throughout the application.
165
+
166
+ 2. **Performance Optimization**: Pre-configuring clients improves performance by ensuring they are ready to use when needed, eliminating on-the-fly configuration that can slow down API calls.
167
+
168
+ 3. **Consistency**: Configuring clients before rendering ensures consistent usage of client configurations across the application, promoting uniformity in API call implementation.
169
+
170
+ 4. **Environment-specific Settings**: This approach facilitates easy configuration of environment-specific settings, such as different base URLs for development, staging, and production environments.
171
+
172
+ 5. **Security**: Configuring clients before rendering enables the setup of essential security measures, including authentication handlers and default scopes, ensuring secure API calls from the outset.
173
+
174
+ 6. **Modularity**: This configuration approach supports a modular architecture, allowing different modules to define their own HTTP client configurations, which can then be combined before rendering the application.
175
+
176
+ By following this approach, you can enhance the efficiency, consistency, security, and modularity of your application's HTTP communication within the Fusion Framework ecosystem.
177
+
178
+ ### Configuration Options
179
+
180
+ When configuring an HTTP client in the Fusion Framework, you can specify various settings to customize its behavior. The following options are available for configuring an HTTP client:
181
+
182
+ | Property | Description |
183
+ |----------|-------------|
184
+ | `baseUri` | The base URI for the API endpoint. |
185
+ | `defaultScopes` | The default scopes for MSAL authentication. |
186
+ | `selector` | The response selector for processing the response. |
187
+ | `onCreate` | A callback function to execute when the client is created. |
188
+ | `requestHandler` | The request operators for processing outgoing requests. |
189
+ | `responseHandler` | The response operators for processing incoming responses. |
190
+ | `ctor` | The constructor function for a custom client. |
191
+
192
+
193
+ ### Basic configuration
194
+
195
+ To configure a basic HTTP client in the Fusion Framework, you can use the following example. This setup is ideal for simple API consumption that does not require advanced authentication mechanisms.
196
+
197
+ ```typescript
198
+ /** Example of basic configuration for an HTTP client in the Fusion Framework */
199
+ const configure = (configurator: IModulesConfigurator) => {
200
+ /**
201
+ * Configure an HTTP client named 'myClient'.
202
+ * This client is set up to communicate with 'https://api.example.com'.
203
+ */
204
+ configurator.http.configureClient(
205
+ 'myClient',
206
+ 'https://api.example.com'
207
+ );
208
+
209
+ // Additional basic configuration can be added here
25
210
  }
26
211
  ```
27
212
 
28
- ### Callback
213
+ ### Configuration with MSAL Authentication
214
+
215
+ For consuming APIs that require secure authentication, it is recommended to configure an HTTP client with MSAL (Microsoft Authentication Library). The following example demonstrates how to set up an HTTP client with MSAL authentication, specifying a default scope.
216
+
29
217
  ```ts
30
- const configure = async(config) => {
31
- config.http.configureClient(
32
- 'bar',
33
- (client): => {
34
- client.uri = 'https://foo.bar'
35
- client.defaultScopes: ['foobar/.default']
218
+ /**
219
+ * Example: Configuring an HTTP client with MSAL authentication in Fusion Framework
220
+ * This configuration is performed during the initialization phase of the app.
221
+ */
222
+ const configure = (configurator: IModulesConfigurator) => {
223
+ /**
224
+ * Configure an HTTP client named 'msalClient'
225
+ * This client is set up to communicate with 'https://api.example.com'
226
+ * and utilizes MSAL for authentication, specifying a default scope.
227
+ */
228
+ configurator.http.configureClient('msalClient', {
229
+ baseUri: 'https://api.example.com',
230
+ defaultScopes: ['api://example-api/.default'],
231
+ });
232
+
233
+ // Additional configuration can be added here
234
+ }
235
+ ```
236
+
237
+ ### Advanced Configuration
238
+
239
+ #### Configuring a http client with callback
240
+
241
+ You can configure an HTTP client using a callback function, which allows for more dynamic and flexible configuration. Here's an example:
242
+
243
+ ```ts
244
+ /**
245
+ * Example of configuring an HTTP client with a callback in Fusion Framework.
246
+ * This configuration is performed during the initialization phase of the app.
247
+ * The callback function provides more flexibility in setting up the client.
248
+ */
249
+ const configure = (configurator: IModulesConfigurator) => {
250
+ /** Configure an HTTP client named 'callbackClient' using a callback function. */
251
+ configurator.http.configureClient('callbackClient', (client) => {
252
+ /** Set the base URI for API requests */
253
+ client.uri = 'https://api.example.com';
254
+
255
+ /** Add a custom request handler */
256
+ client.requestHandler.add('logger', (request) => {
257
+ console.log('Outgoing request:', request);
258
+ // Perform any asynchronous operations if needed before the request is sent
259
+ });
260
+
261
+ /** Add a custom response handler */
262
+ client.responseHandler.add('errorChecker', (response) => {
263
+ if (!response.ok) {
264
+ console.error('Error in response:', response.status, response.statusText);
265
+ switch(response.status) {
266
+ case 401:
267
+ // Handle unauthorized error
268
+ break;
269
+ case 500:
270
+ // Handle server error
271
+ break;
272
+ default:
273
+ // Handle other errors
274
+ break;
275
+ }
36
276
  }
37
- );
277
+ });
278
+
279
+ /** Set default scopes for authentication. These scopes are required for accessing the specified API. */
280
+ client.defaultScopes = ['api://example-api/.default'];
281
+
282
+ // Additional configuration can be added here
283
+ });
284
+ }
285
+ ```
286
+
287
+
288
+ #### Configuration with custom client
289
+
290
+ You can also configure an HTTP client with a custom client instance. This approach allows you to define a custom client with specific settings and behaviors tailored to your application's requirements.
291
+
292
+ ```ts
293
+ /** example of configuring an HTTP client with a custom client instance */
294
+ class CustomHttpClient implements IHttpClient {
295
+ /** custom implementation */
296
+ }
297
+
298
+ const configure = (configurator: IModulesConfigurator) => {
299
+ /** Configure an HTTP client named 'customClient' with a custom client instance. */
300
+ configurator.http.configureClient('custom', {
301
+ ctor: CustomHttpClient,
302
+ baseUri: 'https://api.example.com',
303
+ });
304
+ }
305
+ ```
306
+
307
+
308
+ ## Working with HTTP clients
309
+
310
+ To create an HTTP client, you can use the `createClient` method provided by the module. This method takes the name of the client you want to create and returns an instance of the HTTP client configured with the specified settings:
311
+
312
+ ```ts
313
+ /**
314
+ * Example: Creating an HTTP client in Fusion Framework
315
+ * Assume a client named 'msalClient' has been configured
316
+ * Assume 'modules' is included in the scope
317
+ */
318
+ const msalClient = modules.http.createClient('msalClient');
319
+ ```
320
+
321
+ Once you have created a client, you can use it to make requests to APIs. The client provides several methods for executing HTTP requests, such as `fetch`, `json`, and `blob`, which return Promises, and `fetch$`, `json$`, and `blob$`, which return observables.
322
+
323
+ ### Async vs Observable Execution
324
+
325
+ The Fusion Framework HTTP module offers developers the flexibility to choose between asynchronous (Promise-based) and observable (RxJS-based) methods for executing HTTP requests. This allows developers to select the approach that best suits their specific use case.
326
+
327
+ It's worth noting that both approaches utilize the same underlying RxJS-based implementation, ensuring consistent behavior regardless of the chosen execution method.
328
+
329
+ > [!TIP]
330
+ > While async methods are more familiar to many developers, observable methods offer additional flexibility and power when dealing with complex data flows or when fine-grained control over the request lifecycle is needed.
331
+
332
+ #### Async Execution
333
+
334
+ For simpler use cases, the module also exposes async methods that return Promises:
335
+
336
+ ```ts
337
+ /** Example of using async execution with the HTTP client */
338
+ msalClient.json<MyDataType>('/api/data')
339
+ .then(data => console.log('Received data:', data))
340
+ .catch(error => console.error('An error occurred:', error))
341
+ .finally(() => console.log('Async operation completed'));
342
+ ```
343
+
344
+ Async execution is beneficial for:
345
+ - Simpler, more familiar syntax for many developers
346
+ - Easy integration with async/await patterns
347
+ - Straightforward error handling with try/catch
348
+
349
+ #### Observable Execution
350
+
351
+ The module uses RxJS observables at its core, which provides powerful stream processing capabilities. Observable methods are denoted with a `$` suffix:
352
+
353
+ ```ts
354
+ /** Example of using observable execution with the HTTP client */
355
+ msalClient.json$<MyDataType>('/api/data').subscribe({
356
+ next: (data) => console.log('Received data:', data),
357
+ error: (error) => console.error('An error occurred:', error),
358
+ complete: () => console.log('Observable completed'),
359
+ });
360
+ ```
361
+
362
+ Observable execution is particularly useful for:
363
+ - Handling real-time data streams
364
+ - Implementing complex data transformations
365
+ - Cancelling ongoing requests
366
+
367
+ ### Working with MSAL
368
+
369
+ When working with MSAL authentication, you can specify the required scopes for each request. By default, the client will use the `defaultScopes` configured for the HTTP client. However, you can also overload the scopes for individual API calls by providing an array of scopes in the request options.
370
+
371
+ > [!IMPORTANT]
372
+ > By default the module will add a request operator which will acquire a token from MSAL before the request is sent. This token is added as a bearer token in the request header.
373
+
374
+ > [!WARNING]
375
+ > The scopes provided in the request options will override the default scopes configured for the client.
376
+
377
+ ```ts
378
+ /**
379
+ * Example: Making a request with custom MSAL scopes
380
+ * This request will be authenticated using the specified scopes.
381
+ */
382
+ msalClient.json('/some-endpoint', {
383
+ scopes: ['api://example-api/.admin']
384
+ })
385
+ ```
386
+
387
+ ### Working with JSON
388
+
389
+ To interact with JSON APIs, you can use the `json` or `json$` methods.
390
+
391
+ - The `json$` method returns an Observable that emits the parsed JSON data.
392
+ - The `json` method returns a promise that resolves when the first value from `json$` is emitted.
393
+ - Both methods automatically parse the response as JSON.
394
+ - They also add standard headers to the request.
395
+ - The response is returned as a `JsonResponse<T>`.
396
+
397
+ > [!TIP]
398
+ > Use [typed responses](#use-typed-responses) to ensure that you're using the correct types.
399
+
400
+ > [!IMPORTANT]
401
+ > - **Request Body**: Will only use `JSON.stringify`, pre-process data if needed.
402
+ > - **Response Body**: Will only use `response.json()`, post-process data if needed.
403
+
404
+ ```ts
405
+ /** Example of using the json method to patch data */
406
+ const data = {
407
+ id: 1,
408
+ name: 'John Doe',
38
409
  }
410
+ /** executing a async request */
411
+ client.json('/some-endpoint', { method: "PATCH", body: data });
412
+ /** executing an observable request */
413
+ client.json$('/some-endpoint', { method: "PATCH", body: data })
39
414
  ```
40
415
 
41
- ## Consumption
416
+ ### Handling Errors
417
+
418
+ When working with async functions and observables, it's important to handle errors properly! The HTTP client provides two custom error types for handling HTTP-related errors:
419
+
420
+ **`HttpResponseError`**: This error is thrown when there's an issue with the HTTP response. It includes the original response object, allowing you to access additional details about the error.
421
+
422
+ **`HttpJsonResponseError`**: This error is used when there's an issue parsing JSON data from the response. It includes the parsed data (if available) in addition to the response object.
423
+
424
+ When using the HTTP client, you can catch these errors and handle them appropriately:
425
+
42
426
  ```ts
43
- const client = modules.http.createClient('foo');
44
- const selector = (response: Response): Promise<FooBar> => response.json();
45
- // stream
46
- client.fetch('/api/admin', {selector, scopes: ['foobar/.admin']}).subscribe(x => console.log(x));
427
+ /** Example of handling errors when using the HTTP client */
428
+ const processError = (error: unknown) => {
429
+ /** Check the type of error and handle it accordingly */
430
+ if (error instanceof HttpJsonResponseError) {
431
+ /** This error will be thrown if there's an issue parsing JSON data */
432
+ console.error('JSON Response Error:', error.message, error.data);
433
+ } else if (error instanceof HttpResponseError) {
434
+ /** This error will be thrown if there's an issue with the HTTP response */
435
+ console.error('HTTP Response Error:', error.message, error.response);
436
+ } else {
437
+ /** Handle other types of errors */
438
+ console.error('Unknown error:', error);
439
+ }
440
+ }
47
441
  // async
48
- client.fetchAsync('/api', {selector}).then(console.log);
442
+ try { const data = await client.json('/some-endpoint'); }
443
+ catch (error) { processError(error) }
444
+ finally { /** handle complete */ }
445
+
446
+ // observable
447
+ client.json('/some-endpoint').subscribe({
448
+ next: (response) => { /** Handle response */ },
449
+ error: processError,
450
+ complete: () => { /** Handle complete */ }
451
+ });
452
+ ```
453
+
454
+ > [!IMPORTANT]
455
+ > Example only logs the error, your application should handle errors appropriately based on the use case.
456
+
457
+ ### Use typed responses
458
+
459
+ When coding in TypeScript and using the HTTP client, it's important to use typed responses. This helps ensure that you handle errors correctly and that you're using the correct types.
460
+
461
+ ```ts
462
+ /** Example of using typed responses with the HTTP client */
463
+ interface User {
464
+ id: number;
465
+ name: string;
466
+ }
467
+
468
+ /**
469
+ * Fetch a user by ID.
470
+ * @param id - The ID of the user to fetch.
471
+ * @returns A promise that resolves to the user data.
472
+ */
473
+ const getUser = (id: number): Promise<User> => client.json<User>(`/users/${id}`);
474
+ ```
475
+
476
+ ### Using Response Selectors
477
+
478
+ A good practice when working with data returned from an API is to use reusable selectors. This helps ensure that you don't have to write the same code over and over again.
479
+
480
+ Selectors are functions that process and transform the raw HTTP response before it's returned to your application. The HTTP client provides built-in selectors for common use cases, such as JSON parsing and blob handling.
481
+
482
+ > [!TIP]
483
+ > When providing selectors, the response type is inferred based on the selector's return type.
484
+
485
+ Here is an example of a selector that checks if a resource exists and a selector that parses a CSV file:
486
+ ```ts
487
+ /**
488
+ * Response selector for processing HTTP responses, like HEAD requests.
489
+ * This selector checks if a resource exists based on the response status.
490
+ * @param response - The HTTP response to process.
491
+ * @returns A boolean indicating whether the resource exists.
492
+ */
493
+ export const resourceExistsSelector = (response: Response): boolean => {
494
+ /** Check if the response status is OK (200-299) */
495
+ if(response.ok) {
496
+ return true;
497
+ /** Check if the response status is Not Found (404) */
498
+ } else if(response.status === 404) {
499
+ return false;
500
+ }
501
+ throw Error(`Unexpected response status: ${response.status}`);
502
+ }
503
+
504
+ /** definition of the CSV data type */
505
+ export type CsvData = string[][];
506
+
507
+ /**
508
+ * Response selector for processing CSV data.
509
+ * This selector parses the response text as CSV data.
510
+ * @param response - The HTTP response to process.
511
+ * @returns The parsed CSV data as a 2D array of strings.
512
+ */
513
+ export const csvSelector: ResponseSelector = async (response: Response): Promise<CsvData> => {
514
+ const text = await response.text();
515
+ return text.split('\n').map(line => line.split(','));
516
+ };
517
+ ```
518
+
519
+ Here is an example of how to use the selectors in your application:
520
+
521
+ ```ts
522
+ import { resourceExistsSelector, csvSelector, type CsvData } from './selectors';
523
+
524
+ /**
525
+ * Check if a resource exists based on its ID.
526
+ * @param client - The HTTP client to use for the request.
527
+ * @param itemId - The ID of the resource to check.
528
+ * @returns A promise that resolves to a boolean indicating whether the resource exists.
529
+ */
530
+ export const hasResource = (client: HttpClient, itemId: string): Promise<boolean> => {
531
+ return client.fetch(`/resource/${itemId}`, {
532
+ method: 'HEAD',
533
+ selector: resourceExistsSelector
534
+ });
535
+ }
536
+
537
+ /**
538
+ * Get CSV data from a file.
539
+ * @param client - The HTTP client to use for the request.
540
+ * @param filename - The name of the CSV file to fetch.
541
+ * @returns A promise that resolves to the parsed CSV data.
542
+ */
543
+ export const getCSVData = (client: HttpClient, filename: string): Promise<CsvData> => {
544
+ return client.fetch(filename, { selector: csvSelector });
545
+ }
49
546
  ```
50
547
 
51
- ## Operators
548
+ #### Reusing Selectors
549
+
550
+ You can reuse selectors across different parts of your application. This helps ensure that you don't have to write the same code multiple times.
551
+
52
552
  ```ts
53
- const client = modules.http.createClient('foo');
54
- const logger = console.debug;
55
- client.requestHandler.add((x: Request) => logger(x));
56
- client.responseHandler.add((x: Request) => logger(x));
553
+ /** example of reusing the json selector */
554
+ import { jsonSelector } from '@equinor/fusion-framework-module-http/selectors';
555
+
556
+ /** definition of the data schema */
557
+ import { schema, SchemaType } from './schema';
558
+
559
+ /**
560
+ * Response selector for parsing JSON data.
561
+ * @param response - The HTTP response to process.
562
+ * @returns The parsed JSON data.
563
+ */
564
+ export const dataParserSelector: ResponseSelector<SchemaType> => async(response) => {
565
+ /** Parse the response, with the default jsonSelector */
566
+ const rawData = await jsonSelector(response);
567
+ /** Parse the data using the schema */
568
+ return schema.parse(rawData);
569
+ }
570
+ ```
571
+
572
+ #### Observable Selectors
573
+
574
+ The `ResponseSelector` type is a generic type that allows you to return `ObservableInput` types. This means that the selector supports Promises, Observables, AsyncIterables, and other types that implement the `ObservableInput` interface.
575
+
576
+ ```ts
577
+ /** example of using an observable selector */
578
+ import { from } from 'rxjs';
579
+ import { switchMap } from 'rxjs/operators';
580
+ import { jsonSelector } from '@equinor/fusion-framework-module-http/selectors';
581
+
582
+ /** definition of the data schema */
583
+ import { schema, SchemaType } from './schema';
584
+
585
+ export const dataParserSelector: ResponseSelector => (response): Observable<SchemaType> => {
586
+ /** convert the response to an observable */
587
+ return from(jsonSelector(response)).pipe(
588
+ /** map the async data using the schema */
589
+ switchMap(schema.parseAsync)
590
+ );
591
+ }
592
+ ```
593
+
594
+ ### Use the abort functionality for cancellable requests
595
+
596
+ When using the HTTP client, it's important to use the abort functionality for cancellable requests. This helps ensure that you don't have to handle the cancellation yourself.
597
+
598
+ ```ts
599
+ /** Example of using the abort functionality with the HTTP client */
600
+ useEffect(() => {
601
+ /** Create an abort controller */
602
+ const abortController = new AbortController();
603
+ try {
604
+ /** Make a request using the client with abort signal */
605
+ client.fetch(
606
+ '/long-running-operation',
607
+ {
608
+ signal: abortController.signal
609
+ }
610
+ ).then(setData);
611
+ } catch (error) {
612
+ /** check if the error is an abort error */
613
+ if ((error as Error).name === 'AbortError') {
614
+ console.log('Request was aborted');
615
+ } else {
616
+ setError(error);
617
+ }
618
+ }
619
+ // Cleanup function to abort the request when the component unmounts
620
+ return () => {
621
+ abortController.abort();
622
+ };
623
+ }, [client]);
624
+ ```
625
+
626
+ > [!NOTE]
627
+ > Using observable streams, the request is aborted when the request is no longer observed.
628
+ > ```ts
629
+ > useEffect(() => {
630
+ > const sub = client.json$('/api').subscribe({
631
+ > next: setData,
632
+ > error: setError
633
+ > });
634
+ > return () => sub.unsubscribe();
635
+ > }, [client]);
636
+
637
+ > [!TIP]
638
+ > `HttpClient.abort` will cancel all ongoing requests.
639
+
640
+ ### Utilize request and response operators
641
+
642
+ The HTTP client provides the ability to add custom request and response operators. These operators allow you to intercept and modify requests before they are sent and responses before they are processed.
643
+
644
+ **Functionality:**
645
+
646
+ - Collection Management: Operators can add, set, get, and manage a collection of operators.
647
+ - Chaining: Operators are processed in sequence, allowing for a chain of modifications.
648
+ - Reusable: Operators can be shared across different operators.
649
+ - Extensible: Custom operators can be created for specific needs.
650
+
651
+ ```ts
652
+ /**
653
+ * Definition of the process operator.
654
+ * @template T - this will be either the request or response object.
655
+ * @template R - this will be the return type of the process operator.
656
+ */
657
+ type ProcessOperator<T, R = T> = (request: T) => R | void | Promise<R | void>;
658
+
659
+ /**
660
+ * interface for process operators
661
+ * @template T - this will be either the request or response object.
662
+ */
663
+ interface IProcessOperators<T> {
664
+ /** Add a process operator to the collection */
665
+ add: (name: string, operator: ProcessOperator<T>) => void;
666
+ /** Set a process operator in the collection */
667
+ set: (name: string, operator: ProcessOperator<T>) => void;
668
+ /** Get a process operator from the collection */
669
+ get: (name: string) => ProcessOperator<T> | undefined;
670
+ /** Remove a process operator from the collection */
671
+ remove: (name: string) => void;
672
+ }
673
+ ```
674
+
675
+ > [!CAUTION]
676
+ > Even though the process operator can return a value, it is not recommended to do so. This can cause unexpected behavior.
677
+
678
+ > [!WARNING]
679
+ > - Handlers are permanent to the client instance.
680
+ > - `add` will throw error if a handler with the same name already exists.
681
+ > - `set` will override existing handlers with the same name.
682
+
683
+ > [!IMPORTANT]
684
+ > Handlers are executed in the order they are added. This means that you should add handlers that are more specific to the end of the list.
685
+
686
+ #### Request Handlers
687
+
688
+ You can add request handlers to modify outgoing requests:
689
+
690
+ ```ts
691
+ /**
692
+ * Example of adding a request handler to set a custom header
693
+ * The request handler implements the `IHttpRequestHandler` which exposes the `setHeader` method.
694
+ */
695
+ client.requestHandler.setHeader('X-Custom-Header', 'CustomValue');
696
+
697
+ /** Example of adding a request handler to log all outgoing requests */
698
+ client.requestHandler.add(
699
+ 'request-logger',
700
+ (request) => {
701
+ console.debug('Outgoing request:', request.url);
702
+ }
703
+ );
704
+ ```
705
+
706
+ #### Response Handlers
707
+
708
+ > [!IMPORTANT]
709
+ > Response operators should not modify the response object directly, this might lead to unexpected behavior, like providing the wrong response to the next operator and the provided response selector.
710
+ > 2nd, there are no good way to infer the response type, so the response object should be returned as is.
711
+
712
+ intercept and modify responses before they are processed:
713
+
714
+ ```ts
715
+ /** Example of adding a response handler to log all incoming responses */
716
+ client.responseHandler.add(
717
+ 'response-logger',
718
+ (response) => {
719
+ console.log('Incoming response:', response.url, response.status);
720
+ }
721
+ );
722
+
723
+ /** example of adding a response handler to validate the response */
724
+ client.responseHandler.add(
725
+ 'response-validator'
726
+ (response) => {
727
+ if (response.status === 401) {
728
+ throw Error('response was 401');
729
+ }
730
+ }
731
+ );
732
+ ```
733
+
734
+ ### Executing Calls
735
+
736
+ The HTTP client provides several methods to execute fetch calls. Here are some examples:
737
+
738
+ ```ts
739
+ /** Example of executing fetch call with the HTTP client */
740
+ client.fetch('/users');
741
+ client.fetch$('/users');
742
+
743
+ /** Example of executing a JSON api call with the HTTP client */
744
+ client.json<Users>('/users');
745
+ client.json$<Users>('/users');
746
+
747
+ /** Example of executing a JSON api call with options */
748
+ client.json<BlogPost>('/posts', {
749
+ method: 'POST',
750
+ body: { title: 'New Post', content: 'Content here' },
751
+ })
752
+
753
+ /** Example of executing a blob call */
754
+ client.blob('/image.jpg').then(
755
+ ({ filename, blob }) => {
756
+ const url = URL.createObjectURL(blob);
757
+ return `<a download='${filename}' href='${url}'>`
758
+ }
759
+ );
760
+
761
+ /** Example of executing named function */
762
+ client.execute<Users>('json', '/users'); // same as client.json<Users>('/users');
763
+
764
+ ```
765
+
766
+ ### Monitoring HTTP Activity
767
+
768
+ The HTTP client provides observables that allow you to monitor all incoming requests and responses. This can be useful for logging, debugging, and tracking network activity in your application.
769
+
770
+ ```ts
771
+ /** Example of monitoring all incoming requests */
772
+ client.request$.subscribe(request => {
773
+ console.log('Incoming request:', request);
774
+ });
775
+
776
+ /** Example of monitoring all incoming responses */
777
+ client.response$.subscribe(response => {
778
+ console.log('Incoming response:', response);
779
+ });
57
780
  ```