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 merge interceptor (#2749)

Gpound.liu6a0c1b7e3abc
diff --git a/packages/network/src/index.ts b/packages/network/src/index.ts
index efcd019d93..4c058f0f96 100644
--- a/packages/network/src/index.ts
+++ b/packages/network/src/index.ts
@@ -33,3 +33,4 @@ export type { HTTPHandlerFn, HTTPInterceptorFn, HTTPInterceptorFnFactory } from
export { RetryInterceptorFactory, type IRetryInterceptorFactoryParams } from './services/http/interceptors/retry-interceptor';
export { ThresholdInterceptorFactory } from './services/http/interceptors/threshold-interceptor';
export { AuthInterceptorFactory, type IAuthInterceptorParams } from './services/http/interceptors/auth-interceptor';
+export { MergeInterceptorFactory } from './services/http/interceptors/merge-interceptor';
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
new file mode 100644
index 0000000000..6f888f42bd
--- /dev/null
+++ b/packages/network/src/services/http/interceptors/__tests__/merge-interceptor.spec.ts
@@ -0,0 +1,108 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { afterEach, beforeEach, describe, expect, it, vitest } from 'vitest';
+
+import type { Injector } from '@wendellhu/redi';
+import { HTTPService } from '../../http.service';
+import { createHTTPTestBed, type MockHTTPImplementation } from '../../__testing__/http-testing-utils';
+import { IHTTPImplementation } from '../../implementations/implementation';
+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;
+ let httpImplementation: MockHTTPImplementation;
+ let injector: Injector;
+
+ beforeEach(() => {
+ injector = createHTTPTestBed().injector;
+ httpService = injector.get(HTTPService);
+ httpImplementation = injector.get(IHTTPImplementation) as MockHTTPImplementation;
+
+ vitest.useFakeTimers();
+ });
+
+ afterEach(() => {
+ injector.dispose();
+
+ __TEST_ONLY_RESET_REQUEST_UID_DO_NOT_USE_IN_PRODUCTION();
+
+ vitest.useRealTimers();
+ });
+
+ function emitSuccess(uid: number, body: any) {
+ httpImplementation.getHandler(uid).emitResponse(new HTTPResponse({
+ headers: new HTTPHeaders(),
+ status: 200,
+ statusText: 'Request Succeeded',
+ body,
+ }));
+ }
+
+ it('two requests were created, but only one was a real request', async () => {
+ const path = 'http://example.com';
+ interface Request { ids: string[] };
+ interface Response { list: number[] };
+ const response: Response = { list: [1, 2] };
+ httpService.registerHTTPInterceptor({
+ priority: 999,
+ interceptor: MergeInterceptorFactory<Request, Response>({
+ isMatch(config) {
+ return config.url === path;
+ },
+ getParamsFromRequest(config) {
+ const body = config.requestParams?.body as { ids: string[] };
+ return body;
+ },
+
+ mergeParamsToRequest(list, currentConfig) {
+ const ids = list.reduce((a, b) => {
+ a.push(...b.ids);
+ return a;
+ }, [] as string[]);
+ return new HTTPRequest(currentConfig.method, currentConfig.url, {
+ headers: currentConfig.headers,
+ responseType: currentConfig.responseType,
+ withCredentials: currentConfig.withCredentials,
+ body: { ids },
+ });
+ },
+ }),
+ });
+
+ const request1 = httpService.post<Response>(path, { body: { ids: [1] } });
+ const request2 = httpService.post<Response>(path, { body: { ids: [2] } });
+
+ request1.then((e) => {
+ expect((e as HTTPResponse<Response>).body.list).toEqual(response.list);
+ });
+ request2.then((e) => {
+ expect((e as HTTPResponse<Response>).body.list).toEqual(response.list);
+ });
+
+ await vitest.advanceTimersByTimeAsync(1200);
+
+ // The first request created does not result in a real request
+ expect(() => httpImplementation.getHandler(0)).toThrowError();
+ expect(() => httpImplementation.getHandler(1)).toThrowError();
+
+ // The first two create requests and the last merge result in a new request, so the sequence number is 2
+ emitSuccess(2, response);
+ });
+});
diff --git a/packages/network/src/services/http/interceptors/merge-interceptor.ts b/packages/network/src/services/http/interceptors/merge-interceptor.ts
new file mode 100644
index 0000000000..09128d308e
--- /dev/null
+++ b/packages/network/src/services/http/interceptors/merge-interceptor.ts
@@ -0,0 +1,133 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { Observable } from 'rxjs';
+import type { HTTPRequest } from '../request';
+import { HTTPEventType, HTTPResponse } from '../response';
+import type { HTTPHandlerFn } from '../interceptor';
+
+const createDefaultFetchCheck = (time = 300) => {
+ const noop = () => { };
+ let cancel = noop;
+ return (_currentConfig: HTTPRequest) => {
+ return new Promise<boolean>((res) => {
+ cancel();
+ const t = setTimeout(() => {
+ res(true);
+ }, time);
+ cancel = () => {
+ clearTimeout(t);
+ res(false);
+ };
+ });
+ };
+};
+
+const createDistributeResult = <T, C>() => {
+ return (result: C, list: T[]) => {
+ return list.map((config) => ({ config, result }));
+ };
+};
+
+// eslint-disable-next-line max-lines-per-function
+export const MergeInterceptorFactory = <T, C>(config: {
+ /**
+ * Filter requests that need to be merged
+ */
+ isMatch: (requestConfig: HTTPRequest) => boolean;
+ /**
+ * Pre-process request parameters, the return value will be used as input parameters for subsequent operations
+ * The result is used as an index key
+ */
+ getParamsFromRequest: (requestConfig: HTTPRequest) => T;
+ /**
+ * The request parameters are merged to initiate the request
+ */
+ mergeParamsToRequest: (list: T[], requestConfig: HTTPRequest) => HTTPRequest;
+
+}, options: {
+ /**
+ * Determine when to initiate a request
+ * By default, requests up to 300ms are automatically aggregated
+ */
+ fetchCheck?: (currentConfig: HTTPRequest) => Promise<boolean>;
+ /**
+ * The result of the request is dispatched based on the request parameters.
+ * By default each request gets the full result of the batch request
+ */
+ distributeResult?: (result: C, list: T[]) => { config: T; result: C }[];
+ } = {}) => {
+ interface IHook { next: (v: HTTPResponse<C>) => void; config: T; error: (error: string) => void };
+ const { isMatch, getParamsFromRequest, mergeParamsToRequest } = config;
+ const { fetchCheck = createDefaultFetchCheck(300), distributeResult = createDistributeResult() } = options;
+ const hookList: IHook[] = [];
+ const getPlainList = (_list: IHook[]) => _list.map((item) => item.config);
+
+ return (requestConfig: HTTPRequest, next: HTTPHandlerFn) => {
+ if (!isMatch(requestConfig)) {
+ return next(requestConfig);
+ }
+ return new Observable<HTTPResponse<C>>((observer) => {
+ const params = getParamsFromRequest(requestConfig);
+ hookList.push({
+ next: (v) => observer.next(v),
+ error: (error) => observer.error(error),
+ config: params,
+ });
+ const list = getPlainList(hookList);
+ fetchCheck(requestConfig).then((isFetch) => {
+ if (isFetch) {
+ // Pin down the queue that currently needs a request.
+ const currentHookList: IHook[] = [];
+ list.forEach((config) => {
+ const index = hookList.findIndex((item) => item.config === config);
+ if (index >= 0) {
+ const [hook] = hookList.splice(index, 1);
+ currentHookList.push(hook);
+ } else {
+ // There's no corresponding callback here. It could be that other operations have been handled and do not need to be handled.
+ }
+ });
+
+ next(mergeParamsToRequest(list, requestConfig)).subscribe({
+ next: (e) => {
+ if (e.type === HTTPEventType.Response) {
+ const body = e.body as C;
+ const configList = distributeResult(body, list);
+ currentHookList.forEach((hookItem) => {
+ const res = configList.find((item) => item.config === hookItem.config);
+ if (res) {
+ const response = new HTTPResponse({
+ body: res.result,
+ headers: e.headers,
+ status: e.status,
+ statusText: e.statusText,
+ });
+ hookItem.next(response);
+ } else {
+ hookItem.error('batch error');
+ }
+ });
+ }
+ },
+ complete: () => observer.complete(),
+ error: (e) => observer.error(e),
+ });
+ }
+ });
+ });
+ };
+};
diff --git a/packages/network/src/services/http/request.ts b/packages/network/src/services/http/request.ts
index 0e2d0fd0a4..afa7f2bc67 100644
--- a/packages/network/src/services/http/request.ts
+++ b/packages/network/src/services/http/request.ts
@@ -43,7 +43,7 @@ export function __TEST_ONLY_RESET_REQUEST_UID_DO_NOT_USE_IN_PRODUCTION() {
export class HTTPRequest {
get headers(): HTTPHeaders { return this.requestParams!.headers; }
get withCredentials(): boolean { return this.requestParams!.withCredentials; }
- get responseType(): string { return this.requestParams!.responseType; }
+ get responseType(): HTTPResponseType { return this.requestParams!.responseType; }
readonly uid = HTTPRequestUID++;