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.
TypeScript boardcollaborationdocdocxexceloffce365officepdfpptpptxpresentationsdksheetslidesspreadsheetuniverwordwordprocessorworkspacexlsx
feat(network): add http auth interceptor (#2424)
Wenzhao Hu066941a50d9e
diff --git a/packages/network/src/index.ts b/packages/network/src/index.tsindex 20237fac2a..dacf02003f 100644--- a/packages/network/src/index.ts+++ b/packages/network/src/index.ts@@ -30,5 +30,6 @@ export {} from './services/web-socket/web-socket.service';export type { IRequestParams, IPostRequestParams } from './services/http/http.service';export type { HTTPHandlerFn, HTTPInterceptorFn, HTTPInterceptorFnFactory } from './services/http/interceptor';-export { retryInterceptor } from './services/http/interceptors/retry-interceptor';+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';diff --git a/packages/network/src/services/http/interceptor.ts b/packages/network/src/services/http/interceptor.tsindex 82833d582f..774ce5588c 100644--- a/packages/network/src/services/http/interceptor.ts+++ b/packages/network/src/services/http/interceptor.ts@@ -16,7 +16,6 @@import type { Observable } from 'rxjs';-import type { IAccessor } from '@wendellhu/redi';import type { HTTPRequest } from './request';import type { HTTPEvent } from './response';@@ -45,5 +44,4 @@ export type HTTPInterceptorFn = (request: HTTPRequest, next: HTTPHandlerFn) => Oexport type RequestPipe<T> = (req: HTTPRequest, finalHandlerFn: HTTPHandlerFn) => Observable<HTTPEvent<T>>;-// eslint-disable-next-line ts/no-explicit-any-export type HTTPInterceptorFnFactory = (accessor: IAccessor, params?: any) => HTTPInterceptorFn;+export type HTTPInterceptorFnFactory<T extends unknown[] = []> = (...args: T) => HTTPInterceptorFn;diff --git a/packages/network/src/services/http/interceptors/__tests__/auth-interceptor.spec.ts b/packages/network/src/services/http/interceptors/__tests__/auth-interceptor.spec.tsnew file mode 100644index 0000000000..e3d6548d05--- /dev/null+++ b/packages/network/src/services/http/interceptors/__tests__/auth-interceptor.spec.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 { 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 { __TEST_ONLY_RESET_REQUEST_UID_DO_NOT_USE_IN_PRODUCTION } from '../../request';+import { HTTPHeaders } from '../../headers';+import { HTTPResponse, HTTPResponseError } from '../../response';+import { AuthInterceptorFactory } from '../auth-interceptor';++describe('test "HTTPAuthInterceptor"', () => {+ 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 emitError(uid: number, errorCode: number) {+ httpImplementation.getHandler(uid).emitError(new HTTPResponseError({+ headers: new HTTPHeaders(),+ status: errorCode,+ statusText: 'Internal Server Error',+ error: new Error('mocked error'),+ }));+ }++ function emitSuccess(uid: number) {+ httpImplementation.getHandler(uid).emitResponse(new HTTPResponse({+ headers: new HTTPHeaders(),+ status: 200,+ statusText: 'Request Succeeded',+ body: {+ text: 'Succeeded',+ },+ }));+ }++ it('should pass though on success', () => new Promise<void>((done) => {+ let error = false;++ httpService.registerHTTPInterceptor({+ priority: 10,+ interceptor: AuthInterceptorFactory({+ errorStatusCodes: [401, 403],+ onAuthError: () => {+ error = true;+ },+ }),+ });++ const request = httpService.get('http://example.com');+ request.then(() => {+ expect(error).toBeFalsy();+ done();+ });++ emitSuccess(0);+ }));++ it('should pass though on other kind of errors', () => new Promise<void>((done) => {+ let error = false;++ httpService.registerHTTPInterceptor({+ priority: 10,+ interceptor: AuthInterceptorFactory({+ errorStatusCodes: [401, 403],+ onAuthError: () => {+ error = true;+ },+ }),+ });++ const request = httpService.get('http://example.com');+ request.catch(() => {+ expect(error).toBeFalsy();+ done();+ });++ emitError(0, 500);+ }));++ it('should call "onAuthError" on error status codes', () => new Promise<void>((done) => {+ let error = false;++ httpService.registerHTTPInterceptor({+ priority: 10,+ interceptor: AuthInterceptorFactory({+ errorStatusCodes: [401, 403],+ onAuthError: () => {+ error = true;+ },+ }),+ });++ const request = httpService.get('http://example.com');+ request.catch(() => {+ expect(error).toBeTruthy();+ done();+ });++ emitError(0, 401);+ }));+});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.tsindex 96ebb4cc2b..bc608c996c 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@@ -22,7 +22,7 @@ import { createHTTPTestBed, type MockHTTPImplementation } from '../../__testing_import { IHTTPImplementation } from '../../implementations/implementation';import { HTTPResponse, HTTPResponseError } from '../../response';import { HTTPHeaders } from '../../headers';-import { retryInterceptor } from '../retry-interceptor';+import { RetryInterceptorFactory } from '../retry-interceptor';import { __TEST_ONLY_RESET_REQUEST_UID_DO_NOT_USE_IN_PRODUCTION } from '../../request';describe('test "HTTPRetryInterceptor"', () => {@@ -69,7 +69,7 @@ describe('test "HTTPRetryInterceptor"', () => {it('should retry the request for 3 times until success', () => new Promise<void>((done) => {httpService.registerHTTPInterceptor({priority: 0,- interceptor: retryInterceptor,+ interceptor: RetryInterceptorFactory(),});const request = httpService.get('http://example.com');@@ -93,7 +93,7 @@ describe('test "HTTPRetryInterceptor"', () => {it('should throw error after attempt for 3 times', () => new Promise<void>((done) => {httpService.registerHTTPInterceptor({priority: 0,- interceptor: retryInterceptor,+ interceptor: RetryInterceptorFactory(),});const request = httpService.get('http://example.com');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.tsindex 52576ad2b3..f596617024 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@@ -59,7 +59,7 @@ describe('test "HTTPThresholdInterceptor"', () => {it('should control parallel requests', () => {httpService.registerHTTPInterceptor({priority: 20,- interceptor: injector.invoke(ThresholdInterceptorFactory),+ interceptor: ThresholdInterceptorFactory(),});const _request1 = httpService.get('http://example.com');@@ -85,7 +85,7 @@ describe('test "HTTPThresholdInterceptor"', () => {it('should support threshold params', () => {httpService.registerHTTPInterceptor({priority: 20,- interceptor: injector.invoke(ThresholdInterceptorFactory, { maxParallel: 2 }),+ interceptor: ThresholdInterceptorFactory({ maxParallel: 2 }),});const _request1 = httpService.get('http://example.com');diff --git a/packages/network/src/services/http/interceptors/auth-interceptor.ts b/packages/network/src/services/http/interceptors/auth-interceptor.tsnew file mode 100644index 0000000000..2e45db62eb--- /dev/null+++ b/packages/network/src/services/http/interceptors/auth-interceptor.ts@@ -0,0 +1,43 @@+/**+ * 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 { catchError, throwError } from 'rxjs';+import type { HTTPInterceptorFn, HTTPInterceptorFnFactory } from '../interceptor';+import { HTTPResponseError } from '../response';++export interface IAuthInterceptorParams {+ errorStatusCodes: number[];+ onAuthError: () => void;+}++export const AuthInterceptorFactory: HTTPInterceptorFnFactory<[IAuthInterceptorParams]> = (params) => {+ const { errorStatusCodes, onAuthError } = params;++ const authInterceptor: HTTPInterceptorFn = (request, next) => {+ return next(request).pipe(+ catchError((error) => {+ if ((error instanceof HTTPResponseError) && errorStatusCodes.some((c) => c === error.status)) {+ onAuthError();+ }++ return throwError(() => error);+ })+ );+ };++ return authInterceptor;+};+diff --git a/packages/network/src/services/http/interceptors/retry-interceptor.ts b/packages/network/src/services/http/interceptors/retry-interceptor.tsindex 56ed1f13cd..dcc51c8a52 100644--- a/packages/network/src/services/http/interceptors/retry-interceptor.ts+++ b/packages/network/src/services/http/interceptors/retry-interceptor.ts@@ -14,28 +14,21 @@* limitations under the License.*/-import { delay, of, throwError } from 'rxjs';-import { concatMap, retryWhen } from 'rxjs/operators';-import type { HTTPInterceptorFn } from '../interceptor';+import { retry } from 'rxjs/operators';+import type { Nullable } from '@univerjs/core';+import type { HTTPInterceptorFnFactory } from '../interceptor';-const MAX_RETRY_ATTEMPTS = 2;+const DEFAULT_MAX_RETRY_ATTEMPTS = 3;const DELAY_INTERVAL = 1000;-// TODO@wzhudev: should fix these deprecated warning here+export interface IRetryInterceptorFactoryParams {+ maxRetryAttempts?: number;+ delayInterval?: number;+}-export const retryInterceptor: HTTPInterceptorFn = (request, next) => {- return next(request).pipe(- retryWhen((errors) => {- return errors.pipe(- concatMap((error, index) => {- if (index > MAX_RETRY_ATTEMPTS) {- return throwError(error);- }-- return of(error);- }),- delay(DELAY_INTERVAL)- );- })- );+export const RetryInterceptorFactory: HTTPInterceptorFnFactory<[Nullable<undefined>, Nullable<IRetryInterceptorFactoryParams>]> = (_accessor, params) => {+ const maxRetryAttempts = params?.maxRetryAttempts ?? DEFAULT_MAX_RETRY_ATTEMPTS;+ const delayInterval = params?.delayInterval ?? DELAY_INTERVAL;+ return (request, next) => next(request).pipe(retry({ delay: delayInterval, count: maxRetryAttempts }));};+diff --git a/packages/network/src/services/http/interceptors/threshold-interceptor.ts b/packages/network/src/services/http/interceptors/threshold-interceptor.tsindex e33bbc7c8b..ad0c80d42c 100644--- a/packages/network/src/services/http/interceptors/threshold-interceptor.ts+++ b/packages/network/src/services/http/interceptors/threshold-interceptor.ts@@ -14,8 +14,8 @@* limitations under the License.*/-import type { IAccessor } from '@wendellhu/redi';import { Observable } from 'rxjs';+import type { Nullable } from '@univerjs/core';import { remove } from '@univerjs/core';import type { HTTPInterceptorFnFactory } from '../interceptor';@@ -24,7 +24,8 @@ export interface IThresholdInterceptorFactoryParams {}type HandlerFn = () => void;-export const ThresholdInterceptorFactory: HTTPInterceptorFnFactory = (_accessor: IAccessor, params?: IThresholdInterceptorFactoryParams) => {++export const ThresholdInterceptorFactory: HTTPInterceptorFnFactory<[Nullable<IThresholdInterceptorFactoryParams>]> = (params) => {/*** The local variable to store handles.*/