@ember-data-mirror/request 5.8.0-alpha.40 → 5.8.0-alpha.41

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/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@ember-data-mirror/request",
3
3
  "description": "⚡️ A simple, small and fast framework-agnostic library to make `fetch` happen",
4
- "version": "5.8.0-alpha.40",
4
+ "version": "5.8.0-alpha.41",
5
5
  "license": "MIT",
6
6
  "author": "Chris Thoburn <runspired@users.noreply.github.com>",
7
7
  "repository": {
@@ -36,14 +36,14 @@
36
36
  "peerDependencies": {},
37
37
  "dependencies": {
38
38
  "@embroider/macros": "^1.18.1",
39
- "@warp-drive-mirror/core": "5.8.0-alpha.40"
39
+ "@warp-drive-mirror/core": "5.8.0-alpha.41"
40
40
  },
41
41
  "devDependencies": {
42
42
  "@babel/core": "^7.28.3",
43
43
  "@babel/plugin-transform-typescript": "^7.28.0",
44
44
  "@babel/preset-env": "^7.28.3",
45
45
  "@babel/preset-typescript": "^7.27.1",
46
- "@warp-drive/internal-config": "5.8.0-alpha.40",
46
+ "@warp-drive/internal-config": "5.8.0-alpha.41",
47
47
  "vite": "^7.1.3"
48
48
  },
49
49
  "volta": {
@@ -1,432 +1,5 @@
1
1
  /// <reference path="./fetch.d.ts" />
2
2
  declare module '@ember-data-mirror/request' {
3
- /**
4
- *
5
- <p align="center">
6
- <img
7
- class="project-logo"
8
- src="https://raw.githubusercontent.com/warp-drive-data/warp-drive/4612c9354e4c54d53327ec2cf21955075ce21294/ember-data-logo-light.svg#gh-light-mode-only"
9
- alt="EmberData RequestManager"
10
- width="240px"
11
- title="EmberData RequestManager"
12
- />
13
- </p>
14
-
15
- <p align="center">⚡️ a simple abstraction over fetch to enable easy management of request/response flows</p>
16
-
17
- This package provides [*Ember*‍**Data**](https://github.com/warp-drive-data/warp-drive/)'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.
18
-
19
- - [Installation](#installation)
20
- - [Basic Usage](#🚀-basic-usage)
21
- - [Architecture](#🪜-architecture)
22
- - [Usage](#usage)
23
- - [Making Requests](#making-requests)
24
- - [Using The Response](#using-the-response)
25
- - [Request Handlers](#handling-requests)
26
- - [Handling Errors](#handling-errors)
27
- - [Handling Abort](#handling-abort)
28
- - [Stream Currying](#stream-currying)
29
- - [Automatic Currying](#automatic-currying-of-stream-and-response)
30
- - [Using as a Service](#using-as-a-service)
31
- - [Using with `@ember-data-mirror/store`](#using-with-ember-datastore)
32
- - [Using with `ember-data`](#using-with-ember-data)
33
-
34
- ---
35
-
36
- ## Installation
37
-
38
- Install using your javascript package manager of choice. For instance with [pnpm](https://pnpm.io/)
39
-
40
- ```sh
41
- pnpm add @ember-data-mirror/request
42
- ```
43
-
44
- ---
45
-
46
- ## 🚀 Basic Usage
47
-
48
- A `RequestManager` provides a request/response flow in which configured handlers are successively given the opportunity to handle, modify, or pass-along a request.
49
-
50
- 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`.
51
-
52
- ```ts
53
- import RequestManager from '@ember-data-mirror/request';
54
- import Fetch from '@ember-data-mirror/request/fetch';
55
- import { apiUrl } from '@ember-data-mirror/request/config';
56
-
57
- // ... create manager and add our Fetch handler
58
- const manager = new RequestManager()
59
- .use([Fetch]);
60
-
61
- // ... execute a request
62
- const response = await manager.request({
63
- url: `${apiUrl}/users`
64
- });
65
- ```
66
-
67
- ---
68
-
69
- ## 🪜 Architecture
70
-
71
- 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.
72
-
73
- Each handler may choose to fulfill the request using some source of data or to pass the request along to other handlers.
74
-
75
- The same or a separate instance of a `RequestManager` may also be used to fulfill requests issued by [*Ember*‍**Data**{Store}](https://github.com/warp-drive-data/warp-drive/tree/main/packages/store)
76
-
77
- 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
78
- and return hydrated responses, requests issued directly to the RequestManager
79
- will skip the in-memory cache and return raw responses.
80
-
81
- ---
82
-
83
- ## Usage
84
-
85
- ```ts
86
- const userList = await manager.request({
87
- url: `/api/v1/users.list`
88
- });
89
-
90
- const users = userList.content;
91
- ```
92
-
93
- ---
94
-
95
- ### Making Requests
96
-
97
- `RequestManager` has a single asyncronous method as it's API: `request`
98
-
99
- ```ts
100
- class RequestManager {
101
- request<T>(req: RequestInfo): Future<T>;
102
- }
103
- ```
104
-
105
- `manager.request(<RequestInfo>)` accepts an object containing the information
106
- necessary for the request to be handled successfully.
107
-
108
- 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.
109
-
110
- ```ts
111
- interface RequestInfo extends FetchOptions {
112
- op?: string;
113
- store?: Store;
114
-
115
- url: string;
116
- // data that a handler should convert into
117
- // the query (GET) or body (POST)
118
- data?: Record<string, unknown>;
119
-
120
- // options specifically intended for handlers
121
- // to utilize to process the request
122
- options?: Record<string, unknown>;
123
- }
124
- ```
125
-
126
- > **note**
127
- > providing a `signal` is unnecessary as an `AbortController` is automatically provided if none is present.
128
-
129
- ---
130
-
131
- #### Using the Response
132
-
133
- `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.
134
-
135
- ```ts
136
- const usersFuture = manager.request({
137
- url: `/api/v1/users.list`
138
- });
139
- ```
140
-
141
- A `Future` is cancellable via `abort`.
142
-
143
- ```ts
144
- usersFuture.abort();
145
- ```
146
-
147
- 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.
148
-
149
- ```ts
150
- interface Future<T> extends Promise<StructuredDocument<T>> {
151
- abort(): void;
152
-
153
- async getStream(): ReadableStream | null;
154
- }
155
- ```
156
-
157
- A Future resolves or rejects with a `StructuredDocument`.
158
-
159
- ```ts
160
- interface StructuredDocument<T> {
161
- request: RequestInfo;
162
- response: ResponseInfo | null;
163
- content?: T;
164
- error?: Error;
165
- }
166
- ```
167
-
168
- 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.
169
-
170
- 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`.
171
-
172
- ```ts
173
- interface ResponseInfo {
174
- headers?: Record<string, string>;
175
- ok?: boolean;
176
- redirected?: boolean;
177
- status?: HTTPStatusCode;
178
- statusText?: string;
179
- type?: 'basic' | 'cors';
180
- url?: string;
181
- }
182
- ```
183
-
184
- ---
185
-
186
- ### Request Handlers
187
-
188
- Requests are fulfilled by handlers. A handler receives the request context
189
- as well as a `next` function with which to pass along a request to the next
190
- handler if it so chooses.
191
-
192
- A handler may be any object with a `request` method. This allows both stateful and non-stateful
193
- handlers to be utilized.
194
-
195
- If a handler calls `next`, it receives a `Future` which resolves to a `StructuredDocument`
196
- that it can then compose how it sees fit with its own response.
197
-
198
- ```ts
199
-
200
- type NextFn<P> = (req: RequestInfo) => Future<P>;
201
-
202
- interface Handler {
203
- async request<T>(context: RequestContext, next: NextFn<P>): T;
204
- }
205
- ```
206
-
207
- `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.
208
-
209
- ```ts
210
- interface RequestContext<T> {
211
- readonly request: RequestInfo;
212
-
213
- setStream(stream: ReadableStream | Promise<ReadableStream>): void;
214
- setResponse(response: Response | ResponseInfo): void;
215
- }
216
- ```
217
-
218
- A basic `fetch` handler with support for streaming content updates while
219
- the download is still underway might look like the following, where we use
220
- [`response.clone()`](https://developer.mozilla.org/en-US/docs/Web/API/Response/clone) to `tee` the `ReadableStream` into two streams.
221
-
222
- A more efficient handler might read from the response stream, building up the
223
- response content before passing along the chunk downstream.
224
-
225
- ```ts
226
- const FetchHandler = {
227
- async request(context) {
228
- const response = await fetch(context.request);
229
- context.setResponse(reponse);
230
- context.setStream(response.clone().body);
231
-
232
- return response.json();
233
- }
234
- }
235
- ```
236
-
237
- Request handlers are registered by configuring the manager via `use`
238
-
239
- ```ts
240
- manager.use([Handler1, Handler2])
241
- ```
242
-
243
- 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.
244
-
245
- ---
246
-
247
- #### Handling Errors
248
-
249
- Each handler in the chain can catch errors from upstream and choose to
250
- either handle the error, re-throw the error, or throw a new error.
251
-
252
- ```ts
253
- const MAX_RETRIES = 5;
254
-
255
- const Handler = {
256
- async request(context, next) {
257
- let attempts = 0;
258
-
259
- while (attempts < MAX_RETRIES) {
260
- attempts++;
261
- try {
262
- const response = await next(context.request);
263
- return response;
264
- } catch (e) {
265
- if (isTimeoutError(e) && attempts < MAX_RETRIES) {
266
- // retry request
267
- continue;
268
- }
269
- // rethrow if it is not a timeout error
270
- throw e;
271
- }
272
- }
273
- }
274
- }
275
- ```
276
-
277
- ---
278
-
279
- #### Handling Abort
280
-
281
- Aborting a request will reject the current handler in the chain. However,
282
- every handler can potentially catch this error. If your handler needs to
283
- separate AbortError from other Error types, it is recommended to check
284
- `context.request.signal.aborted` (or if a custom controller was supplied `controller.signal.aborted`).
285
-
286
- In this manner it is possible for a request to recover from an abort and
287
- still proceed; however, as a best practice this should be used for necessary
288
- cleanup only and the original AbortError rethrown if the abort signal comes
289
- from the root controller.
290
-
291
- **AbortControllers are Always Present and Always Entangled**
292
-
293
- If the initial request does not supply an [AbortController](https://developer.mozilla.org/en-US/docs/Web/API/AbortController), one will be generated.
294
-
295
- 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.
296
-
297
- 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
298
- entangled with the root controller. If the root controller aborts, so will
299
- any entangled controllers.
300
-
301
- If an entangled controller aborts, the root controller will not abort. This
302
- allows for advanced request-flow scenarios to abort subsections of the request tree without aborting the entire request.
303
-
304
- ---
305
-
306
- #### Stream Currying
307
-
308
- `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.
309
-
310
- For context, it helps to understand a few of the use-cases that RequestManager
311
- is intended to allow.
312
-
313
- - to manage and return streaming content (such as video files)
314
- - to fulfill a request from multiple sources or by splitting one request into multiple requests
315
- - for instance one API call for a user and another for the user's friends
316
- - or e.g. fulfilling part of the request from one source (one API, in-memory, localStorage, IndexedDB
317
- etc.) and the rest from another source (a different API, a WebWorker, etc.)
318
- - to coalesce multiple requests
319
- - to decorate a request with additional info
320
- - e.g. an Auth handler that ensures the correct tokens or headers or cookies are attached.
321
-
322
-
323
- `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
324
- code *while chunks are still being received by the browser*.
325
-
326
- 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**.
327
-
328
- 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.
329
-
330
- 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
331
- has not been called by the time that the handler's request method has resolved.
332
-
333
- 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.
334
-
335
- ```ts
336
- context.setStream(future.getStream());
337
- ```
338
-
339
- 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.
340
-
341
- Of course, any handler may choose to read and handle the stream, and return either no stream or a different stream in the process.
342
-
343
- ---
344
-
345
- #### Automatic Currying of Stream and Response
346
-
347
- 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;`.
348
-
349
- 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.
350
-
351
- 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>)`.
352
-
353
- In the case of the `Future` being returned, `Stream` proxying is automatic and immediate and does not wait for the `Future` to resolve.
354
-
355
- ---
356
-
357
- #### Using with `@ember-data-mirror/store`
358
-
359
- To have a request service unique to a Store:
360
-
361
- ```ts
362
- import Store, { CacheHandler } from '@ember-data-mirror/store';
363
- import RequestManager from '@ember-data-mirror/request';
364
- import Fetch from '@ember-data-mirror/request/fetch';
365
-
366
- class extends Store {
367
- requestManager = new RequestManager()
368
- .use([Fetch])
369
- .useCache(CacheHandler);
370
- }
371
- ```
372
-
373
- ---
374
-
375
- ### Using as a Service
376
-
377
- Some 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/).
378
-
379
- *services/request.ts*
380
- ```ts
381
- import { CacheHandler } from '@ember-data-mirror/store';
382
- import RequestManager from '@ember-data-mirror/request';
383
- import Fetch from '@ember-data-mirror/request/fetch';
384
- import Auth from 'ember-simple-auth/ember-data-handler';
385
-
386
- export default {
387
- create() {
388
- return new RequestManager()
389
- .use([Auth, Fetch])
390
- .use(CacheHandler);
391
- }
392
- }
393
- ```
394
-
395
- ---
396
-
397
- #### Using with `ember-data`
398
-
399
- If using the package [ember-data](https://github.com/warp-drive-data/warp-drive/tree/main/packages/-ember-data),
400
- the following configuration will automatically be done in order to preserve the
401
- legacy [Adapter](https://github.com/warp-drive-data/warp-drive/tree/main/packages/adapter) and
402
- [Serializer](https://github.com/warp-drive-data/warp-drive/tree/main/packages/serializer) behavior.
403
- Additional handlers or a service injection like the above would need to be done by the
404
- consuming application in order to make broader use of `RequestManager`.
405
-
406
- ```ts
407
- import Store from 'ember-data-mirror/store';
408
- import { CacheHandler } from '@ember-data-mirror/store';
409
- import RequestManager from '@ember-data-mirror/request';
410
- import Fetch from '@ember-data-mirror/request/fetch';
411
- import { LegacyNetworkHandler } from '@ember-data-mirror/legacy-compat';
412
-
413
- export default class extends Store {
414
- requestManager = new RequestManager()
415
- .use([LegacyNetworkHandler, Fetch])
416
- .useCache(CacheHandler);
417
- }
418
- ```
419
-
420
- To provide a different configuration, import and extend `ember-data/store`. The
421
- default configuration will be ignored if the `requestManager` property is set,
422
- though the store will still register the CacheHandler.
423
-
424
- For usage of the store's `requestManager` via `store.request(<req>)` see the
425
- {@link Store} documentation.
426
-
427
- *
428
- * @module
429
- */
430
3
  export * from "@warp-drive-mirror/core/request";
431
4
  export { RequestManager as default } from "@warp-drive-mirror/core";
432
5
  export type { RequestContext, ImmutableRequestInfo, RequestInfo, ResponseInfo, StructuredDocument, StructuredErrorDocument, StructuredDataDocument } from "@warp-drive-mirror/core/types/request";