Skip to content

Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.

feat(network): add stream method for SSE (#5347)

Evan Hu079196d57aee
diff --git a/packages/network/src/services/http/http.service.ts b/packages/network/src/services/http/http.service.ts
index 3890a61a76..5bd22758a2 100644
--- a/packages/network/src/services/http/http.service.ts
+++ b/packages/network/src/services/http/http.service.ts
@@ -19,7 +19,7 @@ import type { Observable } from 'rxjs';
import type { HTTPResponseType } from './http';
import type { HTTPHandlerFn, HTTPInterceptorFn, RequestPipe } from './interceptor';
import type { HTTPRequestMethod } from './request';
-import type { HTTPEvent } from './response';
+import type { HTTPEvent, HTTPResponse } from './response';
import { Disposable, remove, toDisposable } from '@univerjs/core';
import { firstValueFrom, of } from 'rxjs';
import { concatMap } from 'rxjs/operators';
@@ -100,54 +100,39 @@ export class HTTPService extends Disposable {
return toDisposable(() => remove(this._interceptors, interceptor));
}
- get<T>(url: string, params?: IRequestParams): Promise<HTTPEvent<T>> {
- return this._request<T>('GET', url, params);
+ get<T>(url: string, params?: IRequestParams): Promise<HTTPResponse<T>> {
+ return this.request<T>('GET', url, params);
}
- post<T>(url: string, params?: IPostRequestParams): Promise<HTTPEvent<T>> {
- return this._request<T>('POST', url, params);
+ post<T>(url: string, params?: IPostRequestParams): Promise<HTTPResponse<T>> {
+ return this.request<T>('POST', url, params);
}
- put<T>(url: string, params?: IPostRequestParams): Promise<HTTPEvent<T>> {
- return this._request<T>('PUT', url, params);
+ put<T>(url: string, params?: IPostRequestParams): Promise<HTTPResponse<T>> {
+ return this.request<T>('PUT', url, params);
}
- delete<T>(url: string, params?: IRequestParams): Promise<HTTPEvent<T>> {
- return this._request<T>('DELETE', url, params);
+ delete<T>(url: string, params?: IRequestParams): Promise<HTTPResponse<T>> {
+ return this.request<T>('DELETE', url, params);
}
- patch<T>(url: string, params?: IPostRequestParams): Promise<HTTPEvent<T>> {
- return this._request<T>('PATCH', url, params);
+ patch<T>(url: string, params?: IPostRequestParams): Promise<HTTPResponse<T>> {
+ return this.request<T>('PATCH', url, params);
}
- getSSE<T>(
- method: HTTPRequestMethod,
- url: string,
- _params?: IPostRequestParams
- ): Observable<HTTPEvent<T>> {
- // Things to do when sending a HTTP request:
- // 1. Generate HTTPRequest/HTTPHeader object
- // 2. Call interceptors and finally the HTTP implementation.
- const headers = new HTTPHeaders(_params?.headers);
- const params = new HTTPParams(_params?.params);
- const request = new HTTPRequest(method, url, {
- headers,
- params,
- withCredentials: _params?.withCredentials ?? false,
- reportProgress: true,
- responseType: _params?.responseType ?? 'json',
- body: (['GET', 'DELETE'].includes(method)) ? undefined : (_params as IPostRequestParams)?.body,
- });
-
- return of(request).pipe(concatMap((request) => this._runInterceptorsAndImplementation(request)));
- }
-
- /** The HTTP request implementations */
- private async _request<T>(
+ /**
+ * The HTTP request implementations. Normally you should use the `get`, `post`, `put`, `delete`,
+ * `patch` methods instead.
+ * @param method HTTP request method, e.g. GET, POST, PUT, DELETE, etc.
+ * @param url The URL to send the request to.
+ * @param options Optional parameters for the request.
+ * @returns A promise that resolves to the HTTP response.
+ */
+ async request<T>(
method: HTTPRequestMethod,
url: string,
options?: IRequestParams
- ): Promise<HTTPEvent<T>> {
+ ): Promise<HTTPResponse<T>> {
// Things to do when sending a HTTP request:
// 1. Generate HTTPRequest/HTTPHeader object
// 2. Call interceptors and finally the HTTP implementation.
@@ -169,7 +154,55 @@ export class HTTPService extends Disposable {
// The event$ may emit multiple values, but we only care about the first one.
// We may need to care about other events (especially progress events) in the future.
const result = await firstValueFrom(events$);
- return result;
+ return result as HTTPResponse<T>;
+ }
+
+ /**
+ * Send an HTTP request. It returns an observable that emits HTTP events. For example, it can be used to
+ * send Server-Sent Events (SSE) requests.
+ * @deprecated Please use `stream` method instead.
+ * @param method HTTP request method, e.g. GET, POST, PUT, DELETE, etc.
+ * @param url The URL to send the request to.
+ * @param _params Optional parameters for the request.
+ * @returns An observable of the HTTP event.
+ */
+ stream<T>(
+ method: HTTPRequestMethod,
+ url: string,
+ _params?: IRequestParams
+ ): Observable<HTTPEvent<T>> {
+ return this.getSSE<T>(method, url, _params);
+ }
+
+ /**
+ * Send a Server-Sent Events (SSE) request. It returns an observable that emits HTTP events. It is the observable
+ * pair of the `request` method.
+ * @deprecated Please use `stream` method instead.
+ * @param method HTTP request method, e.g. GET, POST, PUT, DELETE, etc.
+ * @param url The URL to send the request to.
+ * @param _params Optional parameters for the request.
+ * @returns An observable of the HTTP event.
+ */
+ getSSE<T>(
+ method: HTTPRequestMethod,
+ url: string,
+ _params?: IPostRequestParams
+ ): Observable<HTTPEvent<T>> {
+ // Things to do when sending a HTTP request:
+ // 1. Generate HTTPRequest/HTTPHeader object
+ // 2. Call interceptors and finally the HTTP implementation.
+ const headers = new HTTPHeaders(_params?.headers);
+ const params = new HTTPParams(_params?.params);
+ const request = new HTTPRequest(method, url, {
+ headers,
+ params,
+ withCredentials: _params?.withCredentials ?? false,
+ reportProgress: true,
+ responseType: _params?.responseType ?? 'json',
+ body: (['GET', 'DELETE'].includes(method)) ? undefined : (_params as IPostRequestParams)?.body,
+ });
+
+ return of(request).pipe(concatMap((request) => this._runInterceptorsAndImplementation(request)));
}
// eslint-disable-next-line ts/no-explicit-any
diff --git a/packages/network/src/services/http/interceptors/__tests__/merge-interceptor.spec.ts b/packages/network/src/services/http/interceptors/__tests__/merge-interceptor.spec.ts
index 0e78043b1a..8a9643433e 100644
--- a/packages/network/src/services/http/interceptors/__tests__/merge-interceptor.spec.ts
+++ b/packages/network/src/services/http/interceptors/__tests__/merge-interceptor.spec.ts
@@ -14,16 +14,17 @@
* limitations under the License.
*/
-import { afterEach, beforeEach, describe, expect, it, vitest } from 'vitest';
-
import type { Injector } from '@univerjs/core';
+
+import type { MockHTTPImplementation } from '../../__testing__/http-testing-utils';
+import { afterEach, beforeEach, describe, expect, it, vitest } from 'vitest';
+import { createHTTPTestBed } from '../../__testing__/http-testing-utils';
+import { HTTPHeaders } from '../../headers';
import { HTTPService } from '../../http.service';
-import { createHTTPTestBed, type MockHTTPImplementation } from '../../__testing__/http-testing-utils';
import { IHTTPImplementation } from '../../implementations/implementation';
+import { __TEST_ONLY_RESET_REQUEST_UID_DO_NOT_USE_IN_PRODUCTION, HTTPRequest } from '../../request';
import { HTTPResponse } from '../../response';
-import { HTTPHeaders } from '../../headers';
import { MergeInterceptorFactory } from '../merge-interceptor';
-import { __TEST_ONLY_RESET_REQUEST_UID_DO_NOT_USE_IN_PRODUCTION, HTTPRequest } from '../../request';
describe('test "HTTPMergeInterceptor"', () => {
let httpService: HTTPService;
@@ -90,10 +91,10 @@ describe('test "HTTPMergeInterceptor"', () => {
const request2 = httpService.post<Response>(path, { body: { ids: [2] } });
request1.then((e) => {
- expect((e as HTTPResponse<Response>).body.list).toEqual(response.list);
+ expect(e.body.list).toEqual(response.list);
});
request2.then((e) => {
- expect((e as HTTPResponse<Response>).body.list).toEqual(response.list);
+ expect(e.body.list).toEqual(response.list);
});
await vitest.advanceTimersByTimeAsync(1200);
diff --git a/packages/network/src/services/http/interceptors/__tests__/retry-interceptor.spec.ts b/packages/network/src/services/http/interceptors/__tests__/retry-interceptor.spec.ts
index bca1aab4ab..076bb23d23 100644
--- a/packages/network/src/services/http/interceptors/__tests__/retry-interceptor.spec.ts
+++ b/packages/network/src/services/http/interceptors/__tests__/retry-interceptor.spec.ts
@@ -16,8 +16,9 @@
import type { Injector } from '@univerjs/core';
+import type { MockHTTPImplementation } from '../../__testing__/http-testing-utils';
import { afterEach, beforeEach, describe, expect, it, vitest } from 'vitest';
-import { createHTTPTestBed, type MockHTTPImplementation } from '../../__testing__/http-testing-utils';
+import { createHTTPTestBed } from '../../__testing__/http-testing-utils';
import { HTTPHeaders } from '../../headers';
import { HTTPService } from '../../http.service';
import { IHTTPImplementation } from '../../implementations/implementation';
@@ -76,7 +77,7 @@ describe('test "HTTPRetryInterceptor"', () => {
const request = httpService.get('http://example.com');
request.then((response) => {
- expect((response as HTTPResponse<{ text: string }>).body).toEqual({ text: 'Succeeded' });
+ expect(response.body).toEqual({ text: 'Succeeded' });
done();
});
diff --git a/packages/network/src/services/http/interceptors/__tests__/threshold-interceptor.spec.ts b/packages/network/src/services/http/interceptors/__tests__/threshold-interceptor.spec.ts
index aa4c927abb..e2551bbb6d 100644
--- a/packages/network/src/services/http/interceptors/__tests__/threshold-interceptor.spec.ts
+++ b/packages/network/src/services/http/interceptors/__tests__/threshold-interceptor.spec.ts
@@ -15,9 +15,10 @@
*/
import type { Injector } from '@univerjs/core';
+import type { MockHTTPImplementation } from '../../__testing__/http-testing-utils';
import { awaitTime } from '@univerjs/core';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
-import { createHTTPTestBed, type MockHTTPImplementation } from '../../__testing__/http-testing-utils';
+import { createHTTPTestBed } from '../../__testing__/http-testing-utils';
import { HTTPHeaders } from '../../headers';
import { HTTPService } from '../../http.service';
import { IHTTPImplementation } from '../../implementations/implementation';
@@ -70,22 +71,22 @@ describe('test "HTTPThresholdInterceptor"', () => {
interceptor: ThresholdInterceptorFactory(),
});
- const request0 = httpService.get('http://example.com');
- const request1 = httpService.get('http://example.com');
+ const request0 = httpService.get<{ text: string }>('http://example.com');
+ const request1 = httpService.get<{ text: string }>('http://example.com');
expect(httpImplementation.getHandler(0)).toBeDefined();
expect(() => httpImplementation.getHandler(1)).toThrowError(); // due to threshold, the second request should not be sent
emitSuccess(0); // when the first request is completed, the second request should be sent
- expect((await request0 as HTTPResponse<{ text: string }>).body.text).toBe('Succeeded');
+ expect((await request0).body.text).toBe('Succeeded');
expect(httpImplementation.getHandler(1)).toBeDefined();
emitSuccess(1); // let the second request get completed
- expect((await request1 as HTTPResponse<{ text: string }>).body.text).toBe('Succeeded');
+ expect((await request1).body.text).toBe('Succeeded');
- const request2 = httpService.get('http://example.com'); // when the third request is sent, it should not be threshold
+ const request2 = httpService.get<{ text: string }>('http://example.com'); // when the third request is sent, it should not be threshold
expect(httpImplementation.getHandler(2)).toBeDefined();
emitSuccess(2);
- expect((await request2 as HTTPResponse<{ text: string }>).body.text).toBe('Succeeded');
+ expect((await request2).body.text).toBe('Succeeded');
});
it('should support threshold params', async () => {
@@ -94,8 +95,8 @@ describe('test "HTTPThresholdInterceptor"', () => {
interceptor: ThresholdInterceptorFactory({ maxParallel: 2 }),
});
- const request0 = httpService.get('http://example.com');
- const request1 = httpService.get('http://example.com');
+ const request0 = httpService.get<{ text: string }>('http://example.com');
+ const request1 = httpService.get<{ text: string }>('http://example.com');
// since the threshold is 2, the second should be sent simultaneously
const handler0 = httpImplementation.getHandler(0);
@@ -105,8 +106,8 @@ describe('test "HTTPThresholdInterceptor"', () => {
emitSuccess(0);
emitSuccess(1);
- expect((await request0 as HTTPResponse<{ text: string }>).body.text).toBe('Succeeded');
- expect((await request1 as HTTPResponse<{ text: string }>).body.text).toBe('Succeeded');
+ expect((await request0).body.text).toBe('Succeeded');
+ expect((await request1).body.text).toBe('Succeeded');
});
it('should support threshold params with errors', async () => {