@ember-data-mirror/request 5.4.0-alpha.49

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/LICENSE.md ADDED
@@ -0,0 +1,11 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (C) 2017-2023 Ember.js contributors
4
+ Portions Copyright (C) 2011-2017 Tilde, Inc. and contributors.
5
+ Portions Copyright (C) 2011 LivingSocial Inc.
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
8
+
9
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
10
+
11
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,478 @@
1
+ <p align="center">
2
+ <img
3
+ class="project-logo"
4
+ src="./ember-data-logo-dark.svg#gh-dark-mode-only"
5
+ alt="EmberData RequestManager"
6
+ width="240px"
7
+ title="EmberData RequestManager"
8
+ />
9
+ <img
10
+ class="project-logo"
11
+ src="./ember-data-logo-light.svg#gh-light-mode-only"
12
+ alt="EmberData RequestManager"
13
+ width="240px"
14
+ title="EmberData RequestManager"
15
+ />
16
+ </p>
17
+
18
+ <p align="center">⚡️ a simple abstraction over fetch to enable easy management of request/response flows</p>
19
+
20
+ This package provides [*Ember***Data**](https://github.com/emberjs/data/)'s `RequestManager`, a framework agnostic library that can be integrated with any Javascript application to make [fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) happen.
21
+
22
+ - [Installation](#installation)
23
+ - [Basic Usage](#🚀-basic-usage)
24
+ - [Architecture](#🪜-architecture)
25
+ - [Usage](#usage)
26
+ - [Making Requests](#making-requests)
27
+ - [Using The Response](#using-the-response)
28
+ - [Request Handlers](#handling-requests)
29
+ - [Handling Errors](#handling-errors)
30
+ - [Handling Abort](#handling-abort)
31
+ - [Stream Currying](#stream-currying)
32
+ - [Automatic Currying](#automatic-currying-of-stream-and-response)
33
+ - [Using as a Service](#using-as-a-service)
34
+ - [Using with `@ember-data-mirror/store`](#using-with-ember-datastore)
35
+ - [Using with `ember-data`](#using-with-ember-data)
36
+
37
+ ## Installation
38
+
39
+ Install using your javascript package manager of choice. For instance with [pnpm](https://pnpm.io/)
40
+
41
+ ```no-highlight
42
+ pnpm add @ember-data-mirror/request
43
+ ```
44
+
45
+ ## 🚀 Basic Usage
46
+
47
+ A `RequestManager` provides a request/response flow in which configured handlers are successively given the opportunity to handle, modify, or pass-along a request.
48
+
49
+ The RequestManager on its own does not know how to fulfill requests. For this we must register at least one handler. A basic `Fetch` handler is provided that will take the request options provided and execute `fetch`.
50
+
51
+ ```ts
52
+ import RequestManager from '@ember-data-mirror/request';
53
+ import Fetch from '@ember-data-mirror/request/fetch';
54
+ import { apiUrl } from './config';
55
+
56
+ // ... create manager and add our Fetch handler
57
+ const manager = new RequestManager();
58
+ manager.use([Fetch]);
59
+
60
+ // ... execute a request
61
+ const response = await manager.request({
62
+ url: `${apiUrl}/users`
63
+ });
64
+ ```
65
+
66
+
67
+ ## 🪜 Architecture
68
+
69
+ A `RequestManager` receives a request and manages fulfillment via configured handlers. It may be used standalone from the rest of *Ember***Data** and is not specific to any library or framework.
70
+
71
+ ```mermaid
72
+ flowchart LR
73
+ A[fa:fa-terminal App] <--> B{{fa:fa-sitemap RequestManager}}
74
+ B <--> C[(fa:fa-database Source)]
75
+ ```
76
+
77
+ Each handler may choose to fulfill the request using some source of data or to pass the request along to other handlers.
78
+
79
+ ```mermaid
80
+ flowchart LR
81
+ A[fa:fa-terminal App] <--> B{{fa:fa-sitemap RequestManager}}
82
+ B <--> C(handler)
83
+ C <--> E(handler)
84
+ E <--> F(handler)
85
+ C <--> D[(fa:fa-database Source)]
86
+ E <--> G[(fa:fa-database Source)]
87
+ F <--> H[(fa:fa-database Source)]
88
+ ```
89
+
90
+ The same or a separate instance of a `RequestManager` may also be used to fulfill requests issued by [*Ember***Data**{Store}](https://github.com/emberjs/data/tree/main/packages/store)
91
+
92
+ ```mermaid
93
+ flowchart LR
94
+ A[fa:fa-terminal App] <--> D{fa:fa-code-fork Store}
95
+ B{{fa:fa-sitemap RequestManager}} <--> C[(fa:fa-database Source)]
96
+ D <--> E[(fa:fa-archive Cache)]
97
+ D <--> B
98
+ click D href "https://github.com/emberjs/data/tree/main/packages/store" "Go to @ember-data-mirror/store" _blank
99
+ click E href "https://github.com/emberjs/data/tree/main/packages/json-api" "Go to @ember-data-mirror/json-api" _blank
100
+ style D color:#58a6ff;
101
+ style E color:#58a6ff;
102
+ ```
103
+
104
+ When the same instance is used by both this allows for simple coordination throughout the application. Requests issued by the Store will use the in-memory cache
105
+ and return hydrated responses, requests issued directly to the RequestManager
106
+ will skip the in-memory cache and return raw responses.
107
+
108
+ ```mermaid
109
+ flowchart LR
110
+ A[fa:fa-terminal App] <--> B{{fa:fa-sitemap RequestManager}}
111
+ B <--> C[(fa:fa-database Source)]
112
+ A <--> D{fa:fa-code-fork Store}
113
+ D <--> E[(fa:fa-archive Cache)]
114
+ D <--> B
115
+ click D href "https://github.com/emberjs/data/tree/main/packages/store" "Go to @ember-data-mirror/store" _blank
116
+ click E href "https://github.com/emberjs/data/tree/main/packages/json-api" "Go to @ember-data-mirror/json-api" _blank
117
+ style D color:#58a6ff;
118
+ style E color:#58a6ff;
119
+ ```
120
+
121
+ ---
122
+
123
+ ## Usage
124
+
125
+ ```ts
126
+ const userList = await manager.request({
127
+ url: `/api/v1/users.list`
128
+ });
129
+
130
+ const users = userList.content;
131
+ ```
132
+
133
+ ---
134
+
135
+ ### Making Requests
136
+
137
+ `RequestManager` has a single asyncronous method as it's API: `request`
138
+
139
+ ```ts
140
+ class RequestManager {
141
+ request<T>(req: RequestInfo): Future<T>;
142
+ }
143
+ ```
144
+
145
+ `manager.request(<RequestInfo>)` accepts an object containing the information
146
+ necessary for the request to be handled successfully.
147
+
148
+ These options extend the [options](https://developer.mozilla.org/en-US/docs/Web/API/fetch#parameters) provided to `fetch`, and can accept a [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request). All properties accepted by Request options and fetch options are valid.
149
+
150
+ ```ts
151
+ interface RequestInfo extends FetchOptions {
152
+ op?: string;
153
+ store?: Store;
154
+
155
+ url: string;
156
+ /**
157
+ * data that a handler should convert into
158
+ * the query (GET) or body (POST)
159
+ */
160
+ data?: Record<string, unknown>;
161
+ /**
162
+ * options specifically intended for handlers
163
+ * to utilize to process the request
164
+ */
165
+ options?: Record<string, unknown>;
166
+ }
167
+ ```
168
+
169
+ > **note**
170
+ > providing a `signal` is unnecessary as an `AbortController` is automatically provided if none is present.
171
+
172
+ ---
173
+
174
+ #### Using the Response
175
+
176
+ `manager.request` returns a `Future`, which allows access to limited information about the request while it is still pending and fulfills with the final state when the request completes and the response has been read.
177
+
178
+ ```ts
179
+ const usersFuture = manager.request({
180
+ url: `/api/v1/users.list`
181
+ });
182
+ ```
183
+
184
+ A `Future` is cancellable via `abort`.
185
+
186
+ ```ts
187
+ usersFuture.abort();
188
+ ```
189
+
190
+ Handlers may *optionally* expose a ReadableStream to the `Future` for streaming data; however, when doing so the handler should not resolve until it has fully read the response stream itself.
191
+
192
+ ```ts
193
+ interface Future<T> extends Promise<StructuredDocument<T>> {
194
+ abort(): void;
195
+
196
+ async getStream(): ReadableStream | null;
197
+ }
198
+ ```
199
+
200
+ A Future resolves or rejects with a `StructuredDocument`.
201
+
202
+ ```ts
203
+ interface StructuredDocument<T> {
204
+ request: RequestInfo;
205
+ response: ResponseInfo | null;
206
+ content?: T;
207
+ error?: Error;
208
+ }
209
+ ```
210
+
211
+ The `RequestInfo` specified by `document.request` is the same as originally provided to `manager.request`. If any handler fulfilled this request using different request info it is not represented here. This contract helps to ensure that `retry` and `caching` are possible since the original arguments are correctly preserved. This also allows handlers to "fork" the request or fulfill from multiple sources without the details of fulfillment muddying the original request.
212
+
213
+ The `ResponseInfo` is a serializable fulfilled subset of a [Response](https://developer.mozilla.org/en-US/docs/Web/API/Response) if set via `setResponse`. If no response was ever set this will be `null`.
214
+
215
+ ```ts
216
+ /**
217
+ * All readonly properties available on a Response
218
+ *
219
+ */
220
+ interface ResponseInfo {
221
+ headers?: Record<string, string>;
222
+ ok?: boolean;
223
+ redirected?: boolean;
224
+ status?: HTTPStatusCode;
225
+ statusText?: string;
226
+ type?: 'basic' | 'cors';
227
+ url?: string;
228
+ }
229
+ ```
230
+
231
+ ---
232
+
233
+ ### Request Handlers
234
+
235
+ Requests are fulfilled by handlers. A handler receives the request context
236
+ as well as a `next` function with which to pass along a request to the next
237
+ handler if it so chooses.
238
+
239
+ A handler may be any object with a `request` method. This allows both stateful and non-stateful
240
+ handlers to be utilized.
241
+
242
+ If a handler calls `next`, it receives a `Future` which resolves to a `StructuredDocument`
243
+ that it can then compose how it sees fit with its own response.
244
+
245
+ ```ts
246
+
247
+ type NextFn<P> = (req: RequestInfo) => Future<P>;
248
+
249
+ interface Handler {
250
+ async request<T>(context: RequestContext, next: NextFn<P>): T;
251
+ }
252
+ ```
253
+
254
+ `RequestContext` contains a readonly version of the RequestInfo as well as a few methods for building up the `StructuredDocument` and `Future` that will be part of the response.
255
+
256
+ ```ts
257
+ interface RequestContext<T> {
258
+ readonly request: RequestInfo;
259
+
260
+ setStream(stream: ReadableStream | Promise<ReadableStream>): void;
261
+ setResponse(response: Response | ResponseInfo): void;
262
+ }
263
+ ```
264
+
265
+ A basic `fetch` handler with support for streaming content updates while
266
+ the download is still underway might look like the following, where we use
267
+ [`response.clone()`](https://developer.mozilla.org/en-US/docs/Web/API/Response/clone) to `tee` the `ReadableStream` into two streams.
268
+
269
+ A more efficient handler might read from the response stream, building up the
270
+ response content before passing along the chunk downstream.
271
+
272
+ ```ts
273
+ const FetchHandler = {
274
+ async request(context) {
275
+ const response = await fetch(context.request);
276
+ context.setResponse(reponse);
277
+ context.setStream(response.clone().body);
278
+
279
+ return response.json();
280
+ }
281
+ }
282
+ ```
283
+
284
+ Request handlers are registered by configuring the manager via `use`
285
+
286
+ ```ts
287
+ manager.use([Handler1, Handler2])
288
+ ```
289
+
290
+ Handlers will be invoked in the order they are registered ("fifo", first-in first-out), and may only be registered up until the first request is made. It is recommended but not required to register all handlers at one time in order to ensure explicitly visible handler ordering.
291
+
292
+ ---
293
+
294
+ #### Handling Errors
295
+
296
+ Each handler in the chain can catch errors from upstream and choose to
297
+ either handle the error, re-throw the error, or throw a new error.
298
+
299
+ ```ts
300
+ const MAX_RETRIES = 5;
301
+
302
+ const Handler = {
303
+ async request(context, next) {
304
+ let attempts = 0;
305
+
306
+ while (attempts < MAX_RETRIES) {
307
+ attempts++;
308
+ try {
309
+ const response = await next(context.request);
310
+ return response;
311
+ } catch (e) {
312
+ if (isTimeoutError(e) && attempts < MAX_RETRIES) {
313
+ // retry request
314
+ continue;
315
+ }
316
+ // rethrow if it is not a timeout error
317
+ throw e;
318
+ }
319
+ }
320
+ }
321
+ }
322
+ ```
323
+
324
+ ---
325
+
326
+ #### Handling Abort
327
+
328
+ Aborting a request will reject the current handler in the chain. However,
329
+ every handler can potentially catch this error. If your handler needs to
330
+ separate AbortError from other Error types, it is recommended to check
331
+ `context.request.signal.aborted` (or if a custom controller was supplied `controller.signal.aborted`).
332
+
333
+ In this manner it is possible for a request to recover from an abort and
334
+ still proceed; however, as a best practice this should be used for necessary
335
+ cleanup only and the original AbortError rethrown if the abort signal comes
336
+ from the root controller.
337
+
338
+ **AbortControllers are Always Present and Always Entangled**
339
+
340
+ If the initial request does not supply an [AbortController](https://developer.mozilla.org/en-US/docs/Web/API/AbortController), one will be generated.
341
+
342
+ The [signal](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) for this controller is automatically added to the request passed into the first handler.
343
+
344
+ Each handler has the option to supply a new controller to the request when calling `next`. If a new controller is provided it will be automatically
345
+ entangled with the root controller. If the root controller aborts, so will
346
+ any entangled controllers.
347
+
348
+ If an entangled controller aborts, the root controller will not abort. This
349
+ allows for advanced request-flow scenarios to abort subsections of the request tree without aborting the entire request.
350
+
351
+ ---
352
+
353
+ #### Stream Currying
354
+
355
+ `RequestManager.request` and `next` differ from `fetch` in one **crucial detail** in that the outer Promise resolves only once the response stream has been processed.
356
+
357
+ For context, it helps to understand a few of the use-cases that RequestManager
358
+ is intended to allow.
359
+
360
+ - to manage and return streaming content (such as video files)
361
+ - to fulfill a request from multiple sources or by splitting one request into multiple requests
362
+ - for instance one API call for a user and another for the user's friends
363
+ - or e.g. fulfilling part of the request from one source (one API, in-memory, localStorage, IndexedDB
364
+ etc.) and the rest from another source (a different API, a WebWorker, etc.)
365
+ - to coalesce multiple requests
366
+ - to decorate a request with additional info
367
+ - e.g. an Auth handler that ensures the correct tokens or headers or cookies are attached.
368
+
369
+ `await fetch(<req>)` resolves at the moment headers are received. This allows for the body of the request to be processed as a stream by application
370
+ code *while chunks are still being received by the browser*.
371
+
372
+ When an app chooses to `await response.json()` what occurs is the browser reads the stream to completion and then returns the result. Additionally, this stream may only be read **once**.
373
+
374
+ The `RequestManager` preserves this ability to subscribe to and utilize the stream by either the application or the handler – thereby delivering the full power and flexibility of native APIs – without restricting developers in ways that lead to complicated workarounds.
375
+
376
+ Each handler may call `setStream` only once, but may do so *at any time* until the promise that the handler returns has resolved. The associated promise returned by calling `future.getStream` will resolve with the stream set by `setStream` if that method is called, or `null` if that method
377
+ has not been called by the time that the handler's request method has resolved.
378
+
379
+ Handlers that do not create a stream of their own, but which call `next`, should defensively pipe the stream forward. While this is not required (see automatic currying below) it is better to do so in most cases as otherwise the stream may not become available to downstream handlers or the application until the upstream handler has fully read it.
380
+
381
+ ```ts
382
+ context.setStream(future.getStream());
383
+ ```
384
+
385
+ Handlers that either call `next` multiple times or otherwise have reason to create multiple fetch requests should either choose to return no stream, meaningfully combine the streams, or select a single prioritized stream.
386
+
387
+ Of course, any handler may choose to read and handle the stream, and return either no stream or a different stream in the process.
388
+
389
+ To conditionally stream, you can check if the user has requested the stream with `context.hasRequestedStream`.
390
+
391
+ ---
392
+
393
+ #### Automatic Currying of Stream and Response
394
+
395
+ In order to simplify the common case for handlers which decorate a request, if `next` is called only a single time and `setResponse` was never called by the handler, the response set by the next handler in the chain will be applied to that handler's outcome. For instance, this makes the following pattern possible `return (await next(<req>)).content;`.
396
+
397
+ Similarly, if `next` is called only a single time and neither `setStream` nor `getStream` was called, we automatically curry the stream from the future returned by `next` onto the future returned by the handler.
398
+
399
+ Finally, if the return value of a handler is a `Future`, we curry `content` and `errors` as well, thus enabling the simplest form `return next(<req>)`.
400
+
401
+ In the case of the `Future` being returned, `Stream` proxying is automatic and immediate and does not wait for the `Future` to resolve.
402
+
403
+ ---
404
+
405
+ ### Using as a Service
406
+
407
+ Most applications will desire to have a single `RequestManager` instance, which can be achieved using module-state patterns for singletons, or for [Ember](https://emberjs.com) applications by exporting the manager as a [service](https://guides.emberjs.com/release/services/).
408
+
409
+ *services/request.ts*
410
+ ```ts
411
+ import RequestManager from '@ember-data-mirror/request';
412
+ import Fetch from '@ember-data-mirror/request/fetch';
413
+ import Auth from 'app/services/auth-handler';
414
+
415
+ export default class extends RequestManager {
416
+ constructor(createArgs) {
417
+ super(createArgs);
418
+ this.use([Auth, Fetch]);
419
+ }
420
+ }
421
+ ```
422
+
423
+ ---
424
+
425
+ #### Using with `@ember-data-mirror/store`
426
+
427
+ To have a request service unique to a Store:
428
+
429
+ ```ts
430
+ import Store, { CacheHandler } from '@ember-data-mirror/store';
431
+ import RequestManager from '@ember-data-mirror/request';
432
+ import Fetch from '@ember-data-mirror/request/fetch';
433
+
434
+ class extends Store {
435
+ requestManager = new RequestManager();
436
+
437
+ constructor(args) {
438
+ super(args);
439
+ this.requestManager.use([Fetch]);
440
+ this.requestManager.useCache(CacheHandler);
441
+ }
442
+ }
443
+ ```
444
+
445
+ ---
446
+
447
+ #### Using with `ember-data`
448
+
449
+ If using the package [ember-data](https://github.com/emberjs/data/tree/main/packages/-ember-data),
450
+ the following configuration will automatically be done in order to preserve the
451
+ legacy [Adapter](https://github.com/emberjs/data/tree/main/packages/adapter) and
452
+ [Serializer](https://github.com/emberjs/data/tree/main/packages/serializer) behavior.
453
+ Additional handlers or a service injection like the above would need to be done by the
454
+ consuming application in order to make broader use of `RequestManager`.
455
+
456
+ ```ts
457
+ import Store, { CacheHandler } from 'ember-data-mirror/store';
458
+ import RequestManager from '@ember-data-mirror/request';
459
+ import Fetch from '@ember-data-mirror/request/fetch';
460
+ import { LegacyNetworkHandler } from '@ember-data-mirror/legacy-compat';
461
+
462
+ export default class extends Store {
463
+ requestManager = new RequestManager();
464
+
465
+ constructor(args) {
466
+ super(args);
467
+ this.requestManager.use([LegacyNetworkHandler, Fetch]);
468
+ this.requestManager.useCache(CacheHandler);
469
+ }
470
+ }
471
+ ```
472
+
473
+ To provide a different configuration, import and extend `ember-data/store`. The
474
+ default configuration will be ignored if the `requestManager` property is set,
475
+ though the store will still register the CacheHandler.
476
+
477
+ For usage of the store's `requestManager` via `store.request(<req>)` see the
478
+ [Store](https://api.emberjs.com/ember-data/release/modules/@ember-data%2Fstore) documentation.