forked from angular/angular
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathresponse.ts
More file actions
454 lines (412 loc) Β· 10.9 KB
/
response.ts
File metadata and controls
454 lines (412 loc) Β· 10.9 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
/**
* @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 {HttpHeaders} from './headers';
/**
* Type enumeration for the different kinds of `HttpEvent`.
*
* @publicApi
*/
export enum HttpEventType {
/**
* The request was sent out over the wire.
*/
Sent,
/**
* An upload progress event was received.
*
* Note: The `FetchBackend` doesn't support progress report on uploads.
*/
UploadProgress,
/**
* The response status code and headers were received.
*/
ResponseHeader,
/**
* A download progress event was received.
*/
DownloadProgress,
/**
* The full response including the body was received.
*/
Response,
/**
* A custom event from an interceptor or a backend.
*/
User,
}
/**
* Base interface for progress events.
*
* @publicApi
*/
export interface HttpProgressEvent {
/**
* Progress event type is either upload or download.
*/
type: HttpEventType.DownloadProgress | HttpEventType.UploadProgress;
/**
* Number of bytes uploaded or downloaded.
*/
loaded: number;
/**
* Total number of bytes to upload or download. Depending on the request or
* response, this may not be computable and thus may not be present.
*/
total?: number;
}
/**
* A download progress event.
*
* @publicApi
*/
export interface HttpDownloadProgressEvent extends HttpProgressEvent {
type: HttpEventType.DownloadProgress;
/**
* The partial response body as downloaded so far.
*
* Only present if the responseType was `text`.
*/
partialText?: string;
}
/**
* An upload progress event.
*
* Note: The `FetchBackend` doesn't support progress report on uploads.
*
* @publicApi
*/
export interface HttpUploadProgressEvent extends HttpProgressEvent {
type: HttpEventType.UploadProgress;
}
/**
* An event indicating that the request was sent to the server. Useful
* when a request may be retried multiple times, to distinguish between
* retries on the final event stream.
*
* @publicApi
*/
export interface HttpSentEvent {
type: HttpEventType.Sent;
}
/**
* A user-defined event.
*
* Grouping all custom events under this type ensures they will be handled
* and forwarded by all implementations of interceptors.
*
* @publicApi
*/
export interface HttpUserEvent<T> {
type: HttpEventType.User;
}
/**
* An error that represents a failed attempt to JSON.parse text coming back
* from the server.
*
* It bundles the Error object with the actual response body that failed to parse.
*
*
*/
export interface HttpJsonParseError {
error: Error;
text: string;
}
/**
* Union type for all possible events on the response stream.
*
* Typed according to the expected type of the response.
*
* @publicApi
*/
export type HttpEvent<T> =
| HttpSentEvent
| HttpHeaderResponse
| HttpResponse<T>
| HttpProgressEvent
| HttpUserEvent<T>;
/**
* Base class for both `HttpResponse` and `HttpHeaderResponse`.
*
* @publicApi
*/
export abstract class HttpResponseBase {
/**
* All response headers.
*/
readonly headers: HttpHeaders;
/**
* Response status code.
*/
readonly status: number;
/**
* Textual description of response status code, defaults to OK.
*
* Do not depend on this.
*/
readonly statusText: string;
/**
* URL of the resource retrieved, or null if not available.
*/
readonly url: string | null;
/**
* Whether the status code falls in the 2xx range.
*/
readonly ok: boolean;
/**
* Type of the response, narrowed to either the full response or the header.
*/
// TODO(issue/24571): remove '!'.
readonly type!: HttpEventType.Response | HttpEventType.ResponseHeader;
/**
* Super-constructor for all responses.
*
* The single parameter accepted is an initialization hash. Any properties
* of the response passed there will override the default values.
*/
constructor(
init: {
headers?: HttpHeaders;
status?: number;
statusText?: string;
url?: string;
},
defaultStatus: number = 200,
defaultStatusText: string = 'OK',
) {
// If the hash has values passed, use them to initialize the response.
// Otherwise use the default values.
this.headers = init.headers || new HttpHeaders();
this.status = init.status !== undefined ? init.status : defaultStatus;
this.statusText = init.statusText || defaultStatusText;
this.url = init.url || null;
// Cache the ok value to avoid defining a getter.
this.ok = this.status >= 200 && this.status < 300;
}
}
/**
* A partial HTTP response which only includes the status and header data,
* but no response body.
*
* `HttpHeaderResponse` is a `HttpEvent` available on the response
* event stream, only when progress events are requested.
*
* @publicApi
*/
export class HttpHeaderResponse extends HttpResponseBase {
/**
* Create a new `HttpHeaderResponse` with the given parameters.
*/
constructor(
init: {
headers?: HttpHeaders;
status?: number;
statusText?: string;
url?: string;
} = {},
) {
super(init);
}
override readonly type: HttpEventType.ResponseHeader = HttpEventType.ResponseHeader;
/**
* Copy this `HttpHeaderResponse`, overriding its contents with the
* given parameter hash.
*/
clone(
update: {headers?: HttpHeaders; status?: number; statusText?: string; url?: string} = {},
): HttpHeaderResponse {
// Perform a straightforward initialization of the new HttpHeaderResponse,
// overriding the current parameters with new ones if given.
return new HttpHeaderResponse({
headers: update.headers || this.headers,
status: update.status !== undefined ? update.status : this.status,
statusText: update.statusText || this.statusText,
url: update.url || this.url || undefined,
});
}
}
/**
* A full HTTP response, including a typed response body (which may be `null`
* if one was not returned).
*
* `HttpResponse` is a `HttpEvent` available on the response event
* stream.
*
* @publicApi
*/
export class HttpResponse<T> extends HttpResponseBase {
/**
* The response body, or `null` if one was not returned.
*/
readonly body: T | null;
/**
* Construct a new `HttpResponse`.
*/
constructor(
init: {
body?: T | null;
headers?: HttpHeaders;
status?: number;
statusText?: string;
url?: string;
} = {},
) {
super(init);
this.body = init.body !== undefined ? init.body : null;
}
override readonly type: HttpEventType.Response = HttpEventType.Response;
clone(): HttpResponse<T>;
clone(update: {
headers?: HttpHeaders;
status?: number;
statusText?: string;
url?: string;
}): HttpResponse<T>;
clone<V>(update: {
body?: V | null;
headers?: HttpHeaders;
status?: number;
statusText?: string;
url?: string;
}): HttpResponse<V>;
clone(
update: {
body?: any | null;
headers?: HttpHeaders;
status?: number;
statusText?: string;
url?: string;
} = {},
): HttpResponse<any> {
return new HttpResponse<any>({
body: update.body !== undefined ? update.body : this.body,
headers: update.headers || this.headers,
status: update.status !== undefined ? update.status : this.status,
statusText: update.statusText || this.statusText,
url: update.url || this.url || undefined,
});
}
}
/**
* A response that represents an error or failure, either from a
* non-successful HTTP status, an error while executing the request,
* or some other failure which occurred during the parsing of the response.
*
* Any error returned on the `Observable` response stream will be
* wrapped in an `HttpErrorResponse` to provide additional context about
* the state of the HTTP layer when the error occurred. The error property
* will contain either a wrapped Error object or the error response returned
* from the server.
*
* @publicApi
*/
export class HttpErrorResponse extends HttpResponseBase implements Error {
readonly name = 'HttpErrorResponse';
readonly message: string;
readonly error: any | null;
/**
* Errors are never okay, even when the status code is in the 2xx success range.
*/
override readonly ok = false;
constructor(init: {
error?: any;
headers?: HttpHeaders;
status?: number;
statusText?: string;
url?: string;
}) {
// Initialize with a default status of 0 / Unknown Error.
super(init, 0, 'Unknown Error');
// If the response was successful, then this was a parse error. Otherwise, it was
// a protocol-level failure of some sort. Either the request failed in transit
// or the server returned an unsuccessful status code.
if (this.status >= 200 && this.status < 300) {
this.message = `Http failure during parsing for ${init.url || '(unknown url)'}`;
} else {
this.message = `Http failure response for ${init.url || '(unknown url)'}: ${init.status} ${
init.statusText
}`;
}
this.error = init.error || null;
}
}
/**
* We use these constant to prevent pulling the whole HttpStatusCode enum
* Those are the only ones referenced directly by the framework
*/
export const HTTP_STATUS_CODE_OK = 200;
export const HTTP_STATUS_CODE_NO_CONTENT = 204;
/**
* Http status codes.
* As per https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
* @publicApi
*/
export enum HttpStatusCode {
Continue = 100,
SwitchingProtocols = 101,
Processing = 102,
EarlyHints = 103,
Ok = HTTP_STATUS_CODE_OK,
Created = 201,
Accepted = 202,
NonAuthoritativeInformation = 203,
NoContent = HTTP_STATUS_CODE_NO_CONTENT,
ResetContent = 205,
PartialContent = 206,
MultiStatus = 207,
AlreadyReported = 208,
ImUsed = 226,
MultipleChoices = 300,
MovedPermanently = 301,
Found = 302,
SeeOther = 303,
NotModified = 304,
UseProxy = 305,
Unused = 306,
TemporaryRedirect = 307,
PermanentRedirect = 308,
BadRequest = 400,
Unauthorized = 401,
PaymentRequired = 402,
Forbidden = 403,
NotFound = 404,
MethodNotAllowed = 405,
NotAcceptable = 406,
ProxyAuthenticationRequired = 407,
RequestTimeout = 408,
Conflict = 409,
Gone = 410,
LengthRequired = 411,
PreconditionFailed = 412,
PayloadTooLarge = 413,
UriTooLong = 414,
UnsupportedMediaType = 415,
RangeNotSatisfiable = 416,
ExpectationFailed = 417,
ImATeapot = 418,
MisdirectedRequest = 421,
UnprocessableEntity = 422,
Locked = 423,
FailedDependency = 424,
TooEarly = 425,
UpgradeRequired = 426,
PreconditionRequired = 428,
TooManyRequests = 429,
RequestHeaderFieldsTooLarge = 431,
UnavailableForLegalReasons = 451,
InternalServerError = 500,
NotImplemented = 501,
BadGateway = 502,
ServiceUnavailable = 503,
GatewayTimeout = 504,
HttpVersionNotSupported = 505,
VariantAlsoNegotiates = 506,
InsufficientStorage = 507,
LoopDetected = 508,
NotExtended = 510,
NetworkAuthenticationRequired = 511,
}