-
Notifications
You must be signed in to change notification settings - Fork 27.4k
Expand file tree
/
Copy pathresource.ts
More file actions
463 lines (423 loc) · 16.1 KB
/
Copy pathresource.ts
File metadata and controls
463 lines (423 loc) · 16.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
assertInInjectionContext,
computed,
ɵencapsulateResourceError as encapsulateResourceError,
inject,
Injector,
linkedSignal,
ɵResourceImpl as ResourceImpl,
type ResourceParamsContext,
ResourceStreamItem,
Signal,
signal,
TransferState,
type ValueEqualityFn,
ɵRuntimeError,
ɵRuntimeErrorCode,
} from '@angular/core';
import type {Subscription} from 'rxjs';
import {HttpClient} from './client';
import {HttpHeaders} from './headers';
import {HttpParams} from './params';
import {HttpRequest} from './request';
import {HttpResourceOptions, HttpResourceRef, HttpResourceRequest} from './resource_api';
import {HttpErrorResponse, HttpEventType, HttpProgressEvent} from './response';
import {
CACHE_OPTIONS,
HTTP_TRANSFER_CACHE_ORIGIN_MAP,
retrieveStateFromCache,
} from './transfer_cache';
/**
* Type for the `httpRequest` top-level function, which includes the call signatures for the JSON-
* based `httpRequest` as well as sub-functions for `ArrayBuffer`, `Blob`, and `string` type
* requests.
*
* @publicApi 22.0
*/
export interface HttpResourceFn {
/**
* Create a `Resource` that fetches data with an HTTP GET request to the given URL.
*
* The resource will update when the URL changes via signals.
*
* Uses `HttpClient` to make requests and supports interceptors, testing, and the other features
* of the `HttpClient` API. Data is parsed as JSON by default - use a sub-function of
* `httpResource`, such as `httpResource.text()`, to parse the response differently.
*
* @publicApi 22.0
*/
<TResult = unknown>(
url: (ctx: ResourceParamsContext) => string | undefined,
options: HttpResourceOptions<TResult, unknown> & {defaultValue: NoInfer<TResult>},
): HttpResourceRef<TResult>;
/**
* Create a `Resource` that fetches data with an HTTP GET request to the given URL.
*
* The resource will update when the URL changes via signals.
*
* Uses `HttpClient` to make requests and supports interceptors, testing, and the other features
* of the `HttpClient` API. Data is parsed as JSON by default - use a sub-function of
* `httpResource`, such as `httpResource.text()`, to parse the response differently.
*
* @publicApi 22.0
*/
<TResult = unknown>(
url: (ctx: ResourceParamsContext) => string | undefined,
options?: HttpResourceOptions<TResult, unknown>,
): HttpResourceRef<TResult | undefined>;
/**
* Create a `Resource` that fetches data with the configured HTTP request.
*
* The resource will update when the request changes via signals.
*
* Uses `HttpClient` to make requests and supports interceptors, testing, and the other features
* of the `HttpClient` API. Data is parsed as JSON by default - use a sub-function of
* `httpResource`, such as `httpResource.text()`, to parse the response differently.
*
* @publicApi 22.0
*/
<TResult = unknown>(
request: (ctx: ResourceParamsContext) => HttpResourceRequest | undefined,
options: HttpResourceOptions<TResult, unknown> & {defaultValue: NoInfer<TResult>},
): HttpResourceRef<TResult>;
/**
* Create a `Resource` that fetches data with the configured HTTP request.
*
* The resource will update when the request changes via signals.
*
* Uses `HttpClient` to make requests and supports interceptors, testing, and the other features
* of the `HttpClient` API. Data is parsed as JSON by default - use a sub-function of
* `httpResource`, such as `httpResource.text()`, to parse the response differently.
*
* @publicApi 22.0
*/
<TResult = unknown>(
request: (ctx: ResourceParamsContext) => HttpResourceRequest | undefined,
options?: HttpResourceOptions<TResult, unknown>,
): HttpResourceRef<TResult | undefined>;
/**
* Create a `Resource` that fetches data with the configured HTTP request.
*
* The resource will update when the URL or request changes via signals.
*
* Uses `HttpClient` to make requests and supports interceptors, testing, and the other features
* of the `HttpClient` API. Data is parsed into an `ArrayBuffer`.
*
* @publicApi 22.0
*/
arrayBuffer: {
<TResult = ArrayBuffer>(
url: (ctx: ResourceParamsContext) => string | undefined,
options: HttpResourceOptions<TResult, ArrayBuffer> & {defaultValue: NoInfer<TResult>},
): HttpResourceRef<TResult>;
<TResult = ArrayBuffer>(
url: (ctx: ResourceParamsContext) => string | undefined,
options?: HttpResourceOptions<TResult, ArrayBuffer>,
): HttpResourceRef<TResult | undefined>;
<TResult = ArrayBuffer>(
request: (ctx: ResourceParamsContext) => HttpResourceRequest | undefined,
options: HttpResourceOptions<TResult, ArrayBuffer> & {defaultValue: NoInfer<TResult>},
): HttpResourceRef<TResult>;
<TResult = ArrayBuffer>(
request: (ctx: ResourceParamsContext) => HttpResourceRequest | undefined,
options?: HttpResourceOptions<TResult, ArrayBuffer>,
): HttpResourceRef<TResult | undefined>;
};
/**
* Create a `Resource` that fetches data with the configured HTTP request.
*
* The resource will update when the URL or request changes via signals.
*
* Uses `HttpClient` to make requests and supports interceptors, testing, and the other features
* of the `HttpClient` API. Data is parsed into a `Blob`.
*
* @publicApi 22.0
*/
blob: {
<TResult = Blob>(
url: (ctx: ResourceParamsContext) => string | undefined,
options: HttpResourceOptions<TResult, Blob> & {defaultValue: NoInfer<TResult>},
): HttpResourceRef<TResult>;
<TResult = Blob>(
url: (ctx: ResourceParamsContext) => string | undefined,
options?: HttpResourceOptions<TResult, Blob>,
): HttpResourceRef<TResult | undefined>;
<TResult = Blob>(
request: (ctx: ResourceParamsContext) => HttpResourceRequest | undefined,
options: HttpResourceOptions<TResult, Blob> & {defaultValue: NoInfer<TResult>},
): HttpResourceRef<TResult>;
<TResult = Blob>(
request: (ctx: ResourceParamsContext) => HttpResourceRequest | undefined,
options?: HttpResourceOptions<TResult, Blob>,
): HttpResourceRef<TResult | undefined>;
};
/**
* Create a `Resource` that fetches data with the configured HTTP request.
*
* The resource will update when the URL or request changes via signals.
*
* Uses `HttpClient` to make requests and supports interceptors, testing, and the other features
* of the `HttpClient` API. Data is parsed as a `string`.
*
* @publicApi 22.0
*/
text: {
<TResult = string>(
url: (ctx: ResourceParamsContext) => string | undefined,
options: HttpResourceOptions<TResult, string> & {defaultValue: NoInfer<TResult>},
): HttpResourceRef<TResult>;
<TResult = string>(
url: (ctx: ResourceParamsContext) => string | undefined,
options?: HttpResourceOptions<TResult, string>,
): HttpResourceRef<TResult | undefined>;
<TResult = string>(
request: (ctx: ResourceParamsContext) => HttpResourceRequest | undefined,
options: HttpResourceOptions<TResult, string> & {defaultValue: NoInfer<TResult>},
): HttpResourceRef<TResult>;
<TResult = string>(
request: (ctx: ResourceParamsContext) => HttpResourceRequest | undefined,
options?: HttpResourceOptions<TResult, string>,
): HttpResourceRef<TResult | undefined>;
};
}
/**
* `httpResource` makes a reactive HTTP request and exposes the request status and response value as
* a `WritableResource`. By default, it assumes that the backend will return JSON data. To make a
* request that expects a different kind of data, you can use a sub-constructor of `httpResource`,
* such as `httpResource.text`.
*
* @publicApi 22.0
* @initializerApiFunction
*/
export const httpResource: HttpResourceFn = (() => {
const jsonFn = makeHttpResourceFn<unknown>('json') as HttpResourceFn;
jsonFn.arrayBuffer = makeHttpResourceFn<ArrayBuffer>('arraybuffer');
jsonFn.blob = makeHttpResourceFn('blob');
jsonFn.text = makeHttpResourceFn('text');
return jsonFn;
})();
/**
* The expected response type of the server.
*
* This is used to parse the response appropriately before returning it to
* the requestee.
*/
type ResponseType = 'arraybuffer' | 'blob' | 'json' | 'text';
type RawRequestType =
| ((ctx: ResourceParamsContext) => string | undefined)
| ((ctx: ResourceParamsContext) => HttpResourceRequest | undefined);
function makeHttpResourceFn<TRaw>(responseType: ResponseType) {
return function httpResource<TResult = TRaw>(
request: RawRequestType,
options?: HttpResourceOptions<TResult, TRaw>,
): HttpResourceRef<TResult> {
if (ngDevMode && !options?.injector) {
assertInInjectionContext(httpResource);
}
const injector = options?.injector ?? inject(Injector);
const cacheOptions = injector.get(CACHE_OPTIONS, null, {optional: true});
const transferState = injector.get(TransferState, null, {optional: true});
const originMap = injector.get(HTTP_TRANSFER_CACHE_ORIGIN_MAP, null, {optional: true});
const getInitialStream = (req: HttpRequest<unknown> | undefined) => {
if (cacheOptions && transferState && req) {
const cachedResponse = retrieveStateFromCache(req, cacheOptions, transferState, originMap);
if (cachedResponse) {
try {
const body = cachedResponse.body as TRaw;
const parsed = options?.parse ? options.parse(body) : (body as unknown as TResult);
return signal({value: parsed});
} catch (e) {
if (typeof ngDevMode === 'undefined' || ngDevMode) {
console.warn(
`Angular detected an error while parsing the cached response for the httpResource at \`${req.url}\`. ` +
`The resource will fall back to its default value and try again asynchronously.`,
e,
);
}
}
}
}
return undefined;
};
return new HttpResourceImpl(
injector,
(ctx: ResourceParamsContext) => normalizeRequest(ctx, request, responseType),
options?.defaultValue,
options?.debugName,
options?.parse as (value: unknown) => TResult,
options?.equal as ValueEqualityFn<unknown>,
getInitialStream,
) as HttpResourceRef<TResult>;
};
}
function normalizeRequest(
ctx: ResourceParamsContext,
request: RawRequestType,
responseType: ResponseType,
): HttpRequest<unknown> | undefined {
let unwrappedRequest = typeof request === 'function' ? request(ctx) : request;
if (unwrappedRequest === undefined) {
return undefined;
} else if (typeof unwrappedRequest === 'string') {
unwrappedRequest = {url: unwrappedRequest};
}
const headers =
unwrappedRequest.headers instanceof HttpHeaders
? unwrappedRequest.headers
: new HttpHeaders(
unwrappedRequest.headers as
| Record<string, string | number | Array<string | number>>
| undefined,
);
const params =
unwrappedRequest.params instanceof HttpParams
? unwrappedRequest.params
: new HttpParams({fromObject: unwrappedRequest.params});
return new HttpRequest(
unwrappedRequest.method ?? 'GET',
unwrappedRequest.url,
unwrappedRequest.body ?? null,
{
headers,
params,
reportProgress: unwrappedRequest.reportProgress,
withCredentials: unwrappedRequest.withCredentials,
keepalive: unwrappedRequest.keepalive,
cache: unwrappedRequest.cache as RequestCache,
priority: unwrappedRequest.priority as RequestPriority,
mode: unwrappedRequest.mode as RequestMode,
redirect: unwrappedRequest.redirect as RequestRedirect,
responseType,
context: unwrappedRequest.context,
transferCache: unwrappedRequest.transferCache,
credentials: unwrappedRequest.credentials as RequestCredentials,
referrer: unwrappedRequest.referrer,
referrerPolicy: unwrappedRequest.referrerPolicy as ReferrerPolicy,
integrity: unwrappedRequest.integrity,
timeout: unwrappedRequest.timeout,
},
);
}
class HttpResourceImpl<T>
extends ResourceImpl<T, HttpRequest<unknown> | undefined>
implements HttpResourceRef<T>
{
private client!: HttpClient;
private _headers = linkedSignal({
source: this.extRequest,
computation: () => undefined as HttpHeaders | undefined,
});
private _progress = linkedSignal({
source: this.extRequest,
computation: () => undefined as HttpProgressEvent | undefined,
});
private _statusCode = linkedSignal({
source: this.extRequest,
computation: () => undefined as number | undefined,
});
readonly headers = computed(() =>
this.status() === 'resolved' || this.status() === 'error' ? this._headers() : undefined,
);
readonly progress = this._progress.asReadonly();
readonly statusCode = this._statusCode.asReadonly();
constructor(
injector: Injector,
request: (ctx: ResourceParamsContext) => HttpRequest<T> | undefined,
defaultValue: T,
debugName?: string,
parse?: (value: unknown) => T,
equal?: ValueEqualityFn<unknown>,
getInitialStream?: (
request: HttpRequest<unknown> | undefined,
) => Signal<ResourceStreamItem<T>> | undefined,
) {
super(
request,
({params: request, abortSignal}) => {
let sub: Subscription | undefined;
// In the unlikely case the request returns synchronously we want to make sure the observable
// is subscribe even if it isn't initialized yet.
let aborted = false;
// Track the abort listener so it can be removed if the Observable completes (as a memory
// optimization).
const onAbort = () => {
aborted = true;
sub?.unsubscribe();
};
abortSignal.addEventListener('abort', onAbort);
// Start off stream as undefined.
const stream = signal<ResourceStreamItem<T>>({value: undefined as T});
let resolve: ((value: Signal<ResourceStreamItem<T>>) => void) | undefined;
const promise = new Promise<Signal<ResourceStreamItem<T>>>((r) => (resolve = r));
const send = (value: ResourceStreamItem<T>): void => {
stream.set(value);
resolve?.(stream);
resolve = undefined;
};
sub = this.client.request(request!).subscribe({
next: (event) => {
switch (event.type) {
case HttpEventType.Response:
this._headers.set(event.headers);
this._statusCode.set(event.status);
try {
send({value: parse ? parse(event.body) : (event.body as T)});
} catch (error) {
send({error: encapsulateResourceError(error)});
}
break;
case HttpEventType.DownloadProgress:
this._progress.set(event);
break;
}
},
error: (error) => {
if (error instanceof HttpErrorResponse) {
this._headers.set(error.headers);
this._statusCode.set(error.status);
}
send({error});
abortSignal.removeEventListener('abort', onAbort);
},
complete: () => {
if (resolve) {
send({
error: new ɵRuntimeError(
ɵRuntimeErrorCode.RESOURCE_COMPLETED_BEFORE_PRODUCING_VALUE,
ngDevMode && 'Resource completed before producing a value',
),
});
}
abortSignal.removeEventListener('abort', onAbort);
},
});
if (aborted) {
sub.unsubscribe();
}
return promise;
},
defaultValue,
equal,
debugName,
injector,
undefined,
getInitialStream,
);
this.client = injector.get(HttpClient);
}
override set(value: T): void {
super.set(value);
this._headers.set(undefined);
this._progress.set(undefined);
this._statusCode.set(undefined);
}
// This is a type only override of the method
declare hasValue: () => this is HttpResourceRef<Exclude<T, undefined>>;
}