typedrest 0.5.0 → 0.6.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 (89) hide show
  1. package/README.md +41 -5
  2. package/endpoints/{CachingEndpoint.ts → CachingEndpoint.d.ts} +0 -1
  3. package/endpoints/Endpoint.d.ts +121 -0
  4. package/endpoints/Endpoint.js +1 -1
  5. package/endpoints/{EntryEndpoint.ts → EntryEndpoint.d.ts} +7 -27
  6. package/endpoints/generic/{CollectionEndpoint.ts → CollectionEndpoint.d.ts} +2 -5
  7. package/endpoints/generic/{ETagEndpointBase.ts → ETagEndpointBase.d.ts} +8 -38
  8. package/endpoints/generic/ETagEndpointBase.js +16 -4
  9. package/endpoints/generic/{ElementEndpoint.ts → ElementEndpoint.d.ts} +12 -70
  10. package/endpoints/generic/{GenericCollectionEndpoint.ts → GenericCollectionEndpoint.d.ts} +21 -106
  11. package/endpoints/generic/{IndexerEndpoint.ts → IndexerEndpoint.d.ts} +4 -11
  12. package/endpoints/generic/PartialResponse.d.ts +19 -0
  13. package/endpoints/{index.ts → index.d.ts} +1 -2
  14. package/endpoints/raw/{BlobEndpoint.ts → BlobEndpoint.d.ts} +9 -29
  15. package/endpoints/raw/{UploadEndpoint.ts → UploadEndpoint.d.ts} +4 -18
  16. package/endpoints/reactive/Delay.d.ts +7 -0
  17. package/endpoints/reactive/GenericStreamingCollectionEndpoint.d.ts +32 -0
  18. package/endpoints/reactive/{PollingEndpoint.ts → PollingEndpoint.d.ts} +7 -34
  19. package/endpoints/reactive/SseStreamingEndpoint.d.ts +50 -0
  20. package/endpoints/reactive/{StreamingCollectionEndpoint.ts → StreamingCollectionEndpoint.d.ts} +2 -5
  21. package/endpoints/reactive/{StreamingEndpoint.ts → StreamingEndpoint.d.ts} +5 -27
  22. package/endpoints/rpc/{ActionEndpoint.ts → ActionEndpoint.d.ts} +3 -10
  23. package/endpoints/rpc/{ConsumerEndpoint.ts → ConsumerEndpoint.d.ts} +3 -12
  24. package/endpoints/rpc/{FunctionEndpoint.ts → FunctionEndpoint.d.ts} +3 -14
  25. package/endpoints/rpc/{ProducerEndpoint.ts → ProducerEndpoint.d.ts} +3 -11
  26. package/endpoints/rpc/{RpcEndpointBase.ts → RpcEndpointBase.d.ts} +4 -12
  27. package/errors/DefaultErrorHandler.d.ts +21 -0
  28. package/errors/{Errors.ts → Errors.d.ts} +20 -21
  29. package/http/EntityStream.d.ts +10 -0
  30. package/http/FetchHttpClient.d.ts +15 -0
  31. package/http/FetchHttpClient.js +1 -1
  32. package/http/{HttpClient.ts → HttpClient.d.ts} +1 -3
  33. package/http/HttpContentRange.d.ts +23 -0
  34. package/http/{HttpHeader.ts → HttpHeader.d.ts} +1 -1
  35. package/http/{HttpMethod.ts → HttpMethod.d.ts} +1 -1
  36. package/http/{HttpStatusCode.ts → HttpStatusCode.d.ts} +1 -1
  37. package/http/ResponseCache.d.ts +19 -0
  38. package/http/RetryAfter.d.ts +6 -0
  39. package/http/ServerSentEvents.d.ts +50 -0
  40. package/links/AggregateLinkExtractor.d.ts +17 -0
  41. package/links/HalLinkExtractor.d.ts +13 -0
  42. package/links/HeaderLinkExtractor.d.ts +13 -0
  43. package/links/{Link.ts → Link.d.ts} +6 -2
  44. package/links/{LinkExtractor.ts → LinkExtractor.d.ts} +0 -1
  45. package/package.json +64 -14
  46. package/serializers/JsonSerializer.d.ts +18 -0
  47. package/serializers/{Serializer.ts → Serializer.d.ts} +0 -2
  48. package/endpoints/Endpoint.test.ts +0 -300
  49. package/endpoints/Endpoint.ts +0 -247
  50. package/endpoints/generic/CollectionEndpoint.test.ts +0 -215
  51. package/endpoints/generic/ElementEndpoint.test.ts +0 -262
  52. package/endpoints/generic/GenericCollectionEndpoint.test.ts +0 -123
  53. package/endpoints/generic/IndexerEndpoint.test.ts +0 -12
  54. package/endpoints/generic/PartialResponse.ts +0 -28
  55. package/endpoints/raw/BlobEndpoint.test.ts +0 -52
  56. package/endpoints/raw/UploadEndpoint.test.ts +0 -47
  57. package/endpoints/reactive/Delay.ts +0 -26
  58. package/endpoints/reactive/GenericStreamingCollectionEndpoint.ts +0 -73
  59. package/endpoints/reactive/PollingEndpoint.test.ts +0 -84
  60. package/endpoints/reactive/SseStreamingEndpoint.test.ts +0 -169
  61. package/endpoints/reactive/SseStreamingEndpoint.ts +0 -115
  62. package/endpoints/reactive/StreamingCollectionEndpoint.test.ts +0 -110
  63. package/endpoints/reactive/StreamingEndpoint.test.ts +0 -130
  64. package/endpoints/rpc/ActionEndpoint.test.ts +0 -36
  65. package/endpoints/rpc/ConsumerEndpoint.test.ts +0 -29
  66. package/endpoints/rpc/FunctionEndpoint.test.ts +0 -29
  67. package/endpoints/rpc/ProducerEndpoint.test.ts +0 -32
  68. package/errors/DefaultErrorHandler.ts +0 -65
  69. package/http/EntityStream.ts +0 -40
  70. package/http/FetchHttpClient.ts +0 -26
  71. package/http/HttpContentRange.ts +0 -41
  72. package/http/ResponseCache.ts +0 -25
  73. package/http/RetryAfter.ts +0 -19
  74. package/http/ServerSentEvents.ts +0 -145
  75. package/jest.config.js +0 -12
  76. package/links/AggregateLinkExtractor.ts +0 -28
  77. package/links/HalLinkExtractor.ts +0 -45
  78. package/links/HeaderLinkExtractor.ts +0 -56
  79. package/serializers/JsonSerializer.ts +0 -25
  80. /package/endpoints/generic/{index.ts → index.d.ts} +0 -0
  81. /package/endpoints/raw/{index.ts → index.d.ts} +0 -0
  82. /package/endpoints/reactive/{index.ts → index.d.ts} +0 -0
  83. /package/endpoints/rpc/{index.ts → index.d.ts} +0 -0
  84. /package/errors/{ErrorHandler.ts → ErrorHandler.d.ts} +0 -0
  85. /package/errors/{index.ts → index.d.ts} +0 -0
  86. /package/http/{index.ts → index.d.ts} +0 -0
  87. /package/{index.ts → index.d.ts} +0 -0
  88. /package/links/{index.ts → index.d.ts} +0 -0
  89. /package/serializers/{index.ts → index.d.ts} +0 -0
@@ -1,47 +0,0 @@
1
- import fetchMock from 'jest-fetch-mock';
2
- import { UploadEndpoint } from '.';
3
- import { EntryEndpoint } from '..';
4
- import { HttpMethod, HttpHeader } from '../../http';
5
-
6
- fetchMock.enableMocks();
7
-
8
- beforeEach(() => {
9
- fetchMock.resetMocks();
10
- });
11
-
12
- test('uploadFromRaw', async () => {
13
- const endpoint = new UploadEndpoint(new EntryEndpoint('http://localhost/'), 'endpoint');
14
- const data = new Blob([new Uint8Array([1, 2, 3])], { type: 'mock/type' });
15
-
16
- fetchMock.mockOnceIf(
17
- req => req.method === HttpMethod.Post && req.url === 'http://localhost/endpoint',
18
- async req => {
19
- expect(req.headers.get(HttpHeader.ContentType)).toBe('mock/type');
20
- return {};
21
- }
22
- );
23
- await endpoint.uploadFrom(data);
24
- });
25
-
26
- test('uploadFromForm', async () => {
27
- const endpoint = new UploadEndpoint(new EntryEndpoint('http://localhost/'), 'endpoint', 'data');
28
- const file = new File([new Uint8Array([1, 2, 3])], 'file.dat', { type: 'mock/type' });
29
-
30
- // Spy on FormData.prototype.set to verify what's being set
31
- const setSpy = jest.spyOn(FormData.prototype, 'set');
32
-
33
- fetchMock.mockOnceIf(
34
- req => req.method === HttpMethod.Post && req.url === 'http://localhost/endpoint',
35
- async () => ({})
36
- );
37
-
38
- await endpoint.uploadFrom(file);
39
-
40
- // Verify the FormData was populated correctly with file name and type
41
- expect(setSpy).toHaveBeenCalledWith('data', file, 'file.dat');
42
- const capturedFile = setSpy.mock.calls[0][1] as File;
43
- expect(capturedFile.name).toBe('file.dat');
44
- expect(capturedFile.type).toBe('mock/type');
45
-
46
- setSpy.mockRestore();
47
- });
@@ -1,26 +0,0 @@
1
- /**
2
- * Waits for a specific amount of time.
3
- * @param ms The time to wait in milliseconds.
4
- * @param signal Used to cancel the wait.
5
- * @returns `true` if the time has elapsed; `false` if the wait was cancelled via the `signal`.
6
- */
7
- export function delay(ms: number, signal?: AbortSignal): Promise<boolean> {
8
- return new Promise(resolve => {
9
- if (signal?.aborted) {
10
- resolve(false);
11
- return;
12
- }
13
-
14
- const onAbort = () => {
15
- clearTimeout(timeout);
16
- resolve(false);
17
- };
18
-
19
- const timeout = setTimeout(() => {
20
- signal?.removeEventListener("abort", onAbort);
21
- resolve(true);
22
- }, ms);
23
-
24
- signal?.addEventListener("abort", onAbort, { once: true });
25
- });
26
- }
@@ -1,73 +0,0 @@
1
- import { ElementEndpoint } from "../generic/ElementEndpoint";
2
- import { GenericCollectionEndpoint } from "../generic/GenericCollectionEndpoint";
3
- import { PartialResponse } from "../generic/PartialResponse";
4
- import { delay } from "./Delay";
5
- import { retryAfter } from "../../http";
6
- import { RangeNotSatisfiableError } from "../../errors";
7
-
8
- /**
9
- * Endpoint for a collection of `TEntity`s observable as an append-only stream using long-polling.<br>
10
- * Use {@link StreamingCollectionEndpoint} instead if you wish to use the default {@link ElementEndpoint} type.
11
- * @typeParam TEntity The type of individual elements in the collection.
12
- * @typeParam TElementEndpoint The type of {@link ElementEndpoint} to provide for individual `TEntity`s.
13
- */
14
- export class GenericStreamingCollectionEndpoint<TEntity, TElementEndpoint extends ElementEndpoint<TEntity>> extends GenericCollectionEndpoint<TEntity, TElementEndpoint> {
15
- /**
16
- * The interval in milliseconds to wait between polling requests.
17
- * Automatically updated whenever the server sends a {@link http!HttpHeader.RetryAfter} header.
18
- */
19
- pollingInterval = 3000;
20
-
21
- /**
22
- * @inheritDoc
23
- */
24
- protected async handle(response: Response) {
25
- await super.handle(response);
26
- this.pollingInterval = retryAfter(response) ?? this.pollingInterval;
27
- }
28
-
29
- /**
30
- * Provides a stream of `TEntity`s, polling the server for elements appended to the collection.
31
- * @param startIndex The index of the first element to return. Use a negative value to start with the last `-startIndex` elements ("tail").
32
- * @param signal Used to stop polling.
33
- * @throws {@link errors!AuthenticationError}: {@link http!HttpStatusCode.Unauthorized}
34
- * @throws {@link errors!AuthorizationError}: {@link http!HttpStatusCode.Forbidden}
35
- * @throws {@link errors!HttpError}: Other non-success status code
36
- */
37
- async *stream(startIndex: number = 0, signal?: AbortSignal): AsyncIterableIterator<TEntity> {
38
- let currentStartIndex = startIndex;
39
-
40
- while (!signal?.aborted) {
41
- let response: PartialResponse<TEntity>;
42
- try {
43
- response = (currentStartIndex >= 0)
44
- // Offset
45
- ? await this.readRange(currentStartIndex, undefined, signal)
46
- // Tail
47
- : await this.readRange(undefined, -currentStartIndex, signal);
48
- } catch (err) {
49
- // Aborting is a regular way of ending the stream, not an error
50
- if (signal?.aborted) return;
51
- if (!(err instanceof RangeNotSatisfiableError)) throw err;
52
-
53
- // No new data available yet, keep polling
54
- if (!await delay(this.pollingInterval, signal)) return;
55
- continue;
56
- }
57
-
58
- yield* response.elements;
59
- if (response.endReached) return;
60
-
61
- // Continue polling for more data
62
- if (response.range?.to === undefined) return;
63
- currentStartIndex = response.range.to + 1;
64
-
65
- if (!await delay(this.pollingInterval, signal)) return;
66
- }
67
- }
68
-
69
- /**
70
- * Provides a stream of `TEntity`s using {@link stream}.
71
- */
72
- [Symbol.asyncIterator]() { return this.stream(); }
73
- }
@@ -1,84 +0,0 @@
1
- import fetchMock from 'jest-fetch-mock';
2
- import { PollingEndpoint } from '.';
3
- import { EntryEndpoint } from '..';
4
- import { HttpHeader } from '../../http';
5
-
6
- class MockEntity {
7
- constructor(public id: number, public name: string) { }
8
- }
9
-
10
- fetchMock.enableMocks();
11
- let endpoint: PollingEndpoint<MockEntity>;
12
-
13
- beforeEach(() => {
14
- fetchMock.resetMocks();
15
- endpoint = new PollingEndpoint<MockEntity>(new EntryEndpoint('http://localhost/'), 'endpoint', x => x.id === 3);
16
- endpoint.pollingInterval = 0;
17
- });
18
-
19
- async function collect<T>(stream: AsyncIterable<T>) {
20
- const result: T[] = [];
21
- for await (const element of stream) result.push(element);
22
- return result;
23
- }
24
-
25
- test('stream', async () => {
26
- fetchMock.mockResponses(
27
- '{"id":1,"name":"test"}',
28
- '{"id":2,"name":"test"}',
29
- ['{"id":3,"name":"test"}', { headers: { [HttpHeader.RetryAfter]: '42' } }]
30
- );
31
-
32
- expect(await collect(endpoint.stream())).toEqual([
33
- new MockEntity(1, 'test'),
34
- new MockEntity(2, 'test'),
35
- new MockEntity(3, 'test')
36
- ]);
37
- expect(endpoint.pollingInterval).toBe(42000);
38
- });
39
-
40
- test('streamSkipsUnchanged', async () => {
41
- fetchMock.mockResponses(
42
- '{"id":1,"name":"test"}',
43
- '{"id":1,"name":"test"}',
44
- '{"id":2,"name":"test"}',
45
- '{"id":3,"name":"test"}'
46
- );
47
-
48
- expect(await collect(endpoint.stream())).toEqual([
49
- new MockEntity(1, 'test'),
50
- new MockEntity(2, 'test'),
51
- new MockEntity(3, 'test')
52
- ]);
53
- });
54
-
55
- test('streamAsyncIterator', async () => {
56
- fetchMock.mockResponses('{"id":3,"name":"test"}');
57
-
58
- expect(await collect(endpoint)).toEqual([new MockEntity(3, 'test')]);
59
- });
60
-
61
- test('streamAbort', async () => {
62
- fetchMock.mockResponse('{"id":1,"name":"test"}');
63
- const controller = new AbortController();
64
-
65
- const result: MockEntity[] = [];
66
- for await (const element of endpoint.stream(controller.signal)) {
67
- result.push(element);
68
- controller.abort();
69
- }
70
-
71
- expect(result).toEqual([new MockEntity(1, 'test')]);
72
- });
73
-
74
- test('streamBreak', async () => {
75
- fetchMock.mockResponse('{"id":1,"name":"test"}');
76
-
77
- const result: MockEntity[] = [];
78
- for await (const element of endpoint.stream()) {
79
- result.push(element);
80
- break;
81
- }
82
-
83
- expect(result).toEqual([new MockEntity(1, 'test')]);
84
- });
@@ -1,169 +0,0 @@
1
- /**
2
- * NOTE: The jsdom environment does not expose response bodies as streams, so these tests need the node environment.
3
- * @jest-environment node
4
- */
5
-
6
- import fetchMock from 'jest-fetch-mock';
7
- import { SseStreamingEndpoint } from '.';
8
- import { EntryEndpoint } from '..';
9
- import { ConflictError } from '../../errors';
10
- import { HttpHeader, HttpStatusCode } from '../../http';
11
-
12
- class MockEntity {
13
- constructor(public id: number, public name: string) { }
14
- }
15
-
16
- fetchMock.enableMocks();
17
- let entryEndpoint: EntryEndpoint;
18
- let endpoint: SseStreamingEndpoint<MockEntity>;
19
-
20
- beforeEach(() => {
21
- fetchMock.resetMocks();
22
- entryEndpoint = new EntryEndpoint('http://localhost/');
23
- endpoint = new SseStreamingEndpoint<MockEntity>(entryEndpoint, 'endpoint');
24
- endpoint.autoReconnect = false;
25
- });
26
-
27
- function sseEvent(data: string, type?: string, id?: string) {
28
- return (type ? `event: ${type}\n` : '')
29
- + (id ? `id: ${id}\n` : '')
30
- + `data: ${data}\n\n`;
31
- }
32
-
33
- /**
34
- * Mocks a response that ends the stream for good.<br>
35
- * NOTE: Needs a `null` body because a 204 response must not have one.
36
- */
37
- function mockNoContentOnce() {
38
- fetchMock.mockImplementationOnce(async () => new Response(null, { status: HttpStatusCode.NoContent }));
39
- }
40
-
41
- function requestHeader(index: number, header: HttpHeader) {
42
- return new Headers(fetchMock.mock.calls[index][1]?.headers).get(header);
43
- }
44
-
45
- async function collect<T>(stream: AsyncIterable<T>) {
46
- const result: T[] = [];
47
- for await (const element of stream) result.push(element);
48
- return result;
49
- }
50
-
51
- test('stream', async () => {
52
- fetchMock.mockResponseOnce(
53
- sseEvent('{"id":5,"name":"test1"}')
54
- + sseEvent('{"id":6,"name":"test2"}')
55
- + sseEvent('{"id":7,"name":"test3"}'));
56
-
57
- expect(await collect(endpoint.stream())).toEqual([
58
- new MockEntity(5, 'test1'),
59
- new MockEntity(6, 'test2'),
60
- new MockEntity(7, 'test3')
61
- ]);
62
- expect(requestHeader(0, HttpHeader.Accept)).toBe('text/event-stream');
63
- });
64
-
65
- test('streamAsyncIterator', async () => {
66
- fetchMock.mockResponseOnce(sseEvent('{"id":5,"name":"test1"}'));
67
-
68
- expect(await collect(endpoint)).toEqual([new MockEntity(5, 'test1')]);
69
- });
70
-
71
- test('streamEventTypeFilter', async () => {
72
- endpoint = new SseStreamingEndpoint<MockEntity>(entryEndpoint, 'endpoint', 'update');
73
- endpoint.autoReconnect = false;
74
-
75
- fetchMock.mockResponseOnce(
76
- sseEvent('{"id":1,"name":"skip"}', 'ignored')
77
- + sseEvent('{"id":5,"name":"test1"}', 'update')
78
- + sseEvent('{"id":99,"name":"default"}')
79
- + sseEvent('{"id":6,"name":"test2"}', 'update'));
80
-
81
- expect(await collect(endpoint.stream())).toEqual([
82
- new MockEntity(5, 'test1'),
83
- new MockEntity(6, 'test2')
84
- ]);
85
- });
86
-
87
- test('streamComments', async () => {
88
- fetchMock.mockResponseOnce(': keep-alive\n\n' + sseEvent('{"id":5,"name":"test1"}'));
89
-
90
- expect(await collect(endpoint.stream())).toEqual([new MockEntity(5, 'test1')]);
91
- });
92
-
93
- test('streamMultiLineData', async () => {
94
- fetchMock.mockResponseOnce('data: {"id":5,\ndata: "name":"test1"}\n\n');
95
-
96
- expect(await collect(endpoint.stream())).toEqual([new MockEntity(5, 'test1')]);
97
- });
98
-
99
- test('streamCarriageReturns', async () => {
100
- fetchMock.mockResponseOnce('data: {"id":5,"name":"test1"}\r\n\r\ndata: {"id":6,"name":"test2"}\r\r');
101
-
102
- expect(await collect(endpoint.stream())).toEqual([
103
- new MockEntity(5, 'test1'),
104
- new MockEntity(6, 'test2')
105
- ]);
106
- });
107
-
108
- test('streamError', async () => {
109
- fetchMock.mockResponseOnce('{"message":"my message"}', {
110
- status: HttpStatusCode.Conflict,
111
- headers: { [HttpHeader.ContentType]: 'application/json' }
112
- });
113
-
114
- await expect(collect(endpoint.stream())).rejects.toThrow(new ConflictError('my message', HttpStatusCode.Conflict));
115
- });
116
-
117
- test('streamNoContentCompletes', async () => {
118
- endpoint.autoReconnect = true;
119
- mockNoContentOnce();
120
-
121
- expect(await collect(endpoint.stream())).toEqual([]);
122
- });
123
-
124
- test('streamReconnectsWithLastEventId', async () => {
125
- endpoint.autoReconnect = true;
126
- endpoint.defaultReconnectionInterval = 0;
127
- fetchMock.mockResponseOnce(sseEvent('{"id":5,"name":"test1"}', undefined, '42'));
128
- mockNoContentOnce();
129
-
130
- expect(await collect(endpoint.stream())).toEqual([new MockEntity(5, 'test1')]);
131
- expect(requestHeader(0, HttpHeader.LastEventId)).toBeNull();
132
- expect(requestHeader(1, HttpHeader.LastEventId)).toBe('42');
133
- });
134
-
135
- test('streamReconnectsOnServerError', async () => {
136
- endpoint.autoReconnect = true;
137
- endpoint.defaultReconnectionInterval = 0;
138
- fetchMock.mockResponseOnce('', { status: 503 });
139
- fetchMock.mockResponseOnce(sseEvent('{"id":5,"name":"test1"}'));
140
- mockNoContentOnce();
141
-
142
- expect(await collect(endpoint.stream())).toEqual([new MockEntity(5, 'test1')]);
143
- });
144
-
145
- test('streamHonorsRetryField', async () => {
146
- endpoint.autoReconnect = true;
147
- endpoint.defaultReconnectionInterval = 0;
148
- fetchMock.mockResponseOnce('retry: 42\n\n' + sseEvent('{"id":5,"name":"test1"}'));
149
- mockNoContentOnce();
150
-
151
- const start = Date.now();
152
- expect(await collect(endpoint.stream())).toEqual([new MockEntity(5, 'test1')]);
153
- expect(Date.now() - start).toBeGreaterThanOrEqual(42);
154
- });
155
-
156
- test('streamAbort', async () => {
157
- endpoint.autoReconnect = true;
158
- endpoint.defaultReconnectionInterval = 0;
159
- fetchMock.mockResponse(sseEvent('{"id":5,"name":"test1"}'));
160
- const controller = new AbortController();
161
-
162
- const result: MockEntity[] = [];
163
- for await (const element of endpoint.stream(controller.signal)) {
164
- result.push(element);
165
- controller.abort();
166
- }
167
-
168
- expect(result).toEqual([new MockEntity(5, 'test1')]);
169
- });
@@ -1,115 +0,0 @@
1
- import { Endpoint } from "../Endpoint";
2
- import { delay } from "./Delay";
3
- import { HttpMethod, HttpHeader, HttpStatusCode, SseReader } from "../../http";
4
-
5
- const eventStreamMediaType = "text/event-stream";
6
-
7
- /**
8
- * Endpoint for a stream of `TEntity`s using Server-Sent Events (SSE).<br>
9
- * Sends `Accept: text/event-stream`. By default, transparently reconnects on connection drops or transient errors,
10
- * honoring the server-supplied `retry:` interval and resuming via the {@link http!HttpHeader.LastEventId} header.
11
- * @typeParam TEntity The type of individual elements in the stream.
12
- */
13
- export class SseStreamingEndpoint<TEntity> extends Endpoint {
14
- /**
15
- * Creates a new SSE streaming endpoint.
16
- * @param referrer The endpoint used to navigate to this one.
17
- * @param relativeUri The URI of this endpoint relative to the `referrer`'s. Add a `./` prefix here to imply a trailing slash in the `referrer`'s URI.
18
- * @param eventType If set, only events with this `event:` type are provided; others are ignored. Leave unspecified to provide all events.
19
- */
20
- constructor(referrer: Endpoint, relativeUri: URL | string, private readonly eventType?: string) {
21
- super(referrer, relativeUri);
22
- }
23
-
24
- /**
25
- * Whether to transparently reconnect on connection drops, transient transport errors and 5xx responses.
26
- */
27
- autoReconnect = true;
28
-
29
- /**
30
- * The reconnection interval in milliseconds used when the server has not (yet) supplied one via the SSE `retry:` field.
31
- */
32
- defaultReconnectionInterval = 3000;
33
-
34
- /**
35
- * Provides a stream of `TEntity`s, reconnecting as needed unless {@link autoReconnect} is disabled.
36
- * @param signal Used to close the connection.
37
- * @throws {@link errors!AuthenticationError}: {@link http!HttpStatusCode.Unauthorized}
38
- * @throws {@link errors!AuthorizationError}: {@link http!HttpStatusCode.Forbidden}
39
- * @throws {@link errors!NotFoundError}: {@link http!HttpStatusCode.NotFound} or {@link http!HttpStatusCode.Gone}
40
- * @throws {@link errors!HttpError}: Other non-success status code
41
- */
42
- async *stream(signal?: AbortSignal): AsyncIterableIterator<TEntity> {
43
- const state = { lastEventId: undefined as string | undefined, reconnectionInterval: this.defaultReconnectionInterval };
44
-
45
- while (!signal?.aborted) {
46
- let reconnect: boolean;
47
- try {
48
- reconnect = yield* this.consumeOnce(state, signal);
49
- } catch (err) {
50
- // Aborting is a regular way of ending the stream, not an error
51
- if (signal?.aborted) return;
52
-
53
- // Transport-level failures are the ones worth retrying; anything else is the server telling us no
54
- if (!this.autoReconnect || !SseStreamingEndpoint.isTransient(err)) throw err;
55
- reconnect = true;
56
- }
57
-
58
- if (!reconnect) return;
59
- if (!await delay(state.reconnectionInterval, signal)) return;
60
- }
61
- }
62
-
63
- /**
64
- * Provides a stream of `TEntity`s using {@link stream}.
65
- */
66
- [Symbol.asyncIterator]() { return this.stream(); }
67
-
68
- /**
69
- * Opens a connection and provides events until the stream ends.
70
- * @param state Carries the last event id and the reconnection interval over to the next attempt.
71
- * @param signal Used to close the connection.
72
- * @returns `true` if another connection attempt should be made; `false` if the stream has ended for good.
73
- */
74
- private async *consumeOnce(state: { lastEventId?: string; reconnectionInterval: number; }, signal?: AbortSignal): AsyncGenerator<TEntity, boolean> {
75
- // NOTE: Abort the request when the consumer stops iterating, not just when the caller's signal fires.
76
- const controller = new AbortController();
77
- const onAbort = () => controller.abort();
78
- signal?.addEventListener("abort", onAbort, { once: true });
79
- if (signal?.aborted) controller.abort();
80
-
81
- try {
82
- const headers = new Headers({ [HttpHeader.Accept]: eventStreamMediaType });
83
- if (state.lastEventId) headers.set(HttpHeader.LastEventId, state.lastEventId);
84
-
85
- const response = await this.httpClient.send(this.uri, HttpMethod.Get, controller.signal, headers);
86
- if (response.status === HttpStatusCode.NoContent) return false;
87
- if (this.autoReconnect && response.status >= 500) return true;
88
- await this.handle(response);
89
-
90
- const reader = new SseReader(response);
91
- try {
92
- for await (const event of reader.events()) {
93
- if (this.eventType !== undefined && event.type !== this.eventType) continue;
94
- yield this.serializer.deserialize<TEntity>(event.data);
95
- }
96
- } finally {
97
- state.lastEventId = reader.lastEventId ?? state.lastEventId;
98
- if (reader.reconnectionInterval !== undefined) state.reconnectionInterval = reader.reconnectionInterval;
99
- }
100
-
101
- return this.autoReconnect;
102
- } finally {
103
- signal?.removeEventListener("abort", onAbort);
104
- controller.abort();
105
- }
106
- }
107
-
108
- /**
109
- * Determines whether an error is a transport-level failure that may succeed on a retry.
110
- * The Fetch API reports these as `TypeError`s, while responses the server actually sent become {@link errors!HttpError}s.
111
- */
112
- private static isTransient(err: unknown) {
113
- return err instanceof TypeError;
114
- }
115
- }
@@ -1,110 +0,0 @@
1
- /**
2
- * NOTE: The jsdom environment strips the "Range" request header, so these tests need the node environment.
3
- * @jest-environment node
4
- */
5
-
6
- import fetchMock from 'jest-fetch-mock';
7
- import { StreamingCollectionEndpoint } from '.';
8
- import { EntryEndpoint } from '..';
9
- import { HttpHeader, HttpStatusCode } from '../../http';
10
-
11
- class MockEntity {
12
- constructor(public id: number, public name: string) { }
13
- }
14
-
15
- fetchMock.enableMocks();
16
- let endpoint: StreamingCollectionEndpoint<MockEntity>;
17
-
18
- beforeEach(() => {
19
- fetchMock.resetMocks();
20
- endpoint = new StreamingCollectionEndpoint<MockEntity>(new EntryEndpoint('http://localhost/'), 'endpoint');
21
- endpoint.pollingInterval = 0;
22
- });
23
-
24
- function mockRangeOnce(body: string, contentRange?: string, retryAfterHeader?: string) {
25
- const headers: { [key: string]: string; } = {};
26
- if (contentRange) headers[HttpHeader.ContentRange] = contentRange;
27
- if (retryAfterHeader) headers[HttpHeader.RetryAfter] = retryAfterHeader;
28
-
29
- fetchMock.mockResponseOnce(body, { status: HttpStatusCode.PartialContent, headers });
30
- }
31
-
32
- function requestHeader(index: number, header: HttpHeader) {
33
- return new Headers(fetchMock.mock.calls[index][1]?.headers).get(header);
34
- }
35
-
36
- async function collect<T>(stream: AsyncIterable<T>) {
37
- const result: T[] = [];
38
- for await (const element of stream) result.push(element);
39
- return result;
40
- }
41
-
42
- test('stream', async () => {
43
- mockRangeOnce('[{"id":5,"name":"test1"},{"id":6,"name":"test2"}]', 'elements 0-1/*');
44
- mockRangeOnce('[{"id":7,"name":"test3"}]', 'elements 2-2/3', '42');
45
-
46
- expect(await collect(endpoint.stream())).toEqual([
47
- new MockEntity(5, 'test1'),
48
- new MockEntity(6, 'test2'),
49
- new MockEntity(7, 'test3')
50
- ]);
51
- expect(requestHeader(0, HttpHeader.Range)).toBe('elements=0-');
52
- expect(requestHeader(1, HttpHeader.Range)).toBe('elements=2-');
53
- expect(endpoint.pollingInterval).toBe(42000);
54
- });
55
-
56
- test('streamOffset', async () => {
57
- mockRangeOnce('[{"id":7,"name":"test3"}]', 'elements 2-2/3');
58
-
59
- expect(await collect(endpoint.stream(2))).toEqual([new MockEntity(7, 'test3')]);
60
- expect(requestHeader(0, HttpHeader.Range)).toBe('elements=2-');
61
- });
62
-
63
- test('streamTail', async () => {
64
- mockRangeOnce('[{"id":7,"name":"test3"}]', 'elements 2-2/3');
65
-
66
- expect(await collect(endpoint.stream(-1))).toEqual([new MockEntity(7, 'test3')]);
67
- expect(requestHeader(0, HttpHeader.Range)).toBe('elements=-1');
68
- });
69
-
70
- test('streamAsyncIterator', async () => {
71
- mockRangeOnce('[{"id":5,"name":"test1"}]', 'elements 0-0/1');
72
-
73
- expect(await collect(endpoint)).toEqual([new MockEntity(5, 'test1')]);
74
- });
75
-
76
- test('streamKeepsPollingWhileRangeNotSatisfiable', async () => {
77
- mockRangeOnce('[{"id":5,"name":"test1"}]', 'elements 0-0/*');
78
- fetchMock.mockResponseOnce('', { status: HttpStatusCode.RangeNotSatisfiable });
79
- mockRangeOnce('[{"id":6,"name":"test2"}]', 'elements 1-1/2');
80
-
81
- expect(await collect(endpoint.stream())).toEqual([
82
- new MockEntity(5, 'test1'),
83
- new MockEntity(6, 'test2')
84
- ]);
85
- expect(requestHeader(1, HttpHeader.Range)).toBe('elements=1-');
86
- expect(requestHeader(2, HttpHeader.Range)).toBe('elements=1-');
87
- });
88
-
89
- test('streamEndsWithoutContentRange', async () => {
90
- fetchMock.mockResponseOnce('[{"id":5,"name":"test1"}]');
91
-
92
- expect(await collect(endpoint.stream())).toEqual([new MockEntity(5, 'test1')]);
93
- expect(fetchMock.mock.calls.length).toBe(1);
94
- });
95
-
96
- test('streamAbort', async () => {
97
- fetchMock.mockResponse('[{"id":5,"name":"test1"}]', {
98
- status: HttpStatusCode.PartialContent,
99
- headers: { [HttpHeader.ContentRange]: 'elements 0-0/*' }
100
- });
101
- const controller = new AbortController();
102
-
103
- const result: MockEntity[] = [];
104
- for await (const element of endpoint.stream(0, controller.signal)) {
105
- result.push(element);
106
- controller.abort();
107
- }
108
-
109
- expect(result).toEqual([new MockEntity(5, 'test1')]);
110
- });