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
fix(support): network supports form data (#4950)
Dushusir61d233db9599
diff --git a/packages/network/src/services/http/__testing__/request.spec.ts b/packages/network/src/services/http/__testing__/request.spec.tsnew file mode 100644index 0000000000..e820627c1a--- /dev/null+++ b/packages/network/src/services/http/__testing__/request.spec.ts@@ -0,0 +1,163 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * 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 { beforeEach, describe, expect, it } from 'vitest';+import { ApplicationJSONType, HTTPHeaders } from '../headers';+import { HTTPParams } from '../params';+import { __TEST_ONLY_RESET_REQUEST_UID_DO_NOT_USE_IN_PRODUCTION, HTTPRequest } from '../request';++describe('test class HTTPRequest', () => {+ beforeEach(() => {+ __TEST_ONLY_RESET_REQUEST_UID_DO_NOT_USE_IN_PRODUCTION();+ });++ it('should have incremental UIDs for multiple requests', () => {+ const request1 = new HTTPRequest('GET', 'https://example.com');+ const request2 = new HTTPRequest('GET', 'https://example.com');++ expect(request1.uid).toBe(0);+ expect(request2.uid).toBe(1);+ });++ describe('getUrlWithParams', () => {+ it('should return original URL when no params', () => {+ const request = new HTTPRequest('GET', 'https://example.com');+ expect(request.getUrlWithParams()).toBe('https://example.com');+ });++ it('should append params with ? when URL has no query params', () => {+ const params = new HTTPParams({ key: 'value' });+ const request = new HTTPRequest('GET', 'https://example.com', {+ headers: new HTTPHeaders(),+ params,+ responseType: 'json',+ withCredentials: false,+ });++ expect(request.getUrlWithParams()).toBe('https://example.com?key=value');+ });++ it('should append params with & when URL already has query params', () => {+ const params = new HTTPParams({ key2: 'value2' });+ const request = new HTTPRequest('GET', 'https://example.com?key1=value1', {+ headers: new HTTPHeaders(),+ params,+ responseType: 'json',+ withCredentials: false,+ });++ expect(request.getUrlWithParams()).toBe('https://example.com?key1=value1&key2=value2');+ });+ });++ describe('getBody', () => {+ it('should return null for empty body', () => {+ const request = new HTTPRequest('GET', 'https://example.com', {+ headers: new HTTPHeaders(),+ responseType: 'json',+ withCredentials: false,+ });++ expect(request.getBody()).toBeNull();+ });++ it('should return FormData as is', () => {+ const formData = new FormData();+ const request = new HTTPRequest('POST', 'https://example.com', {+ body: formData,+ headers: new HTTPHeaders(),+ responseType: 'json',+ withCredentials: false,+ });++ expect(request.getBody()).toBe(formData);+ });++ it('should stringify object for JSON content type', () => {+ const body = { name: 'test', value: 123 };+ const headers = new HTTPHeaders({+ 'Content-Type': ApplicationJSONType,+ });++ const request = new HTTPRequest('POST', 'https://example.com', {+ body,+ headers,+ responseType: 'json',+ withCredentials: false,+ });++ expect(request.getBody()).toBe(JSON.stringify(body));+ });++ it('should convert non-object body to string', () => {+ const request = new HTTPRequest('POST', 'https://example.com', {+ body: 123,+ headers: new HTTPHeaders(),+ responseType: 'text',+ withCredentials: false,+ });++ expect(request.getBody()).toBe('123');+ });+ });++ describe('getHeadersInit', () => {+ it('should return headers from HTTPHeaders object', () => {+ const headers = new HTTPHeaders({+ 'X-Custom-Header': 'test',+ Authorization: 'Bearer token',+ });++ const request = new HTTPRequest('GET', 'https://example.com', {+ headers,+ responseType: 'json',+ withCredentials: false,+ });++ const headersInit = request.getHeadersInit();++ expect(headersInit).toHaveProperty('X-Custom-Header'.toLowerCase(), 'test');+ expect(headersInit).toHaveProperty('Authorization'.toLowerCase(), 'Bearer token');+ });++ it('should set Content-Type to application/json for JSON body', () => {+ const headers = new HTTPHeaders();+ const request = new HTTPRequest('POST', 'https://example.com', {+ headers,+ body: { name: 'test' },+ responseType: 'json',+ withCredentials: false,+ });++ const headersInit = request.getHeadersInit();+ expect(headersInit).toHaveProperty('content-type', 'application/json;charset=UTF-8');+ });++ it('should not set Content-Type for FormData body', () => {+ const formData = new FormData();+ const headers = new HTTPHeaders();+ const request = new HTTPRequest('POST', 'https://example.com', {+ headers,+ body: formData,+ responseType: 'json',+ withCredentials: false,+ });++ const headersInit = request.getHeadersInit();+ expect(headersInit).not.toHaveProperty('content-type');+ });+ });+});diff --git a/packages/network/src/services/http/headers.ts b/packages/network/src/services/http/headers.tsindex 2c5f7b0ece..4c6c3c6ba4 100644--- a/packages/network/src/services/http/headers.ts+++ b/packages/network/src/services/http/headers.ts@@ -21,6 +21,18 @@ interface IHeadersConstructorProps {// Header keys in `HTTPHeaders` should be in lower case.export const ApplicationJSONType = 'application/json';+/**+ * Check if the content type is application/json+ * "application/json" or "application/json; charset=utf-8" or ["application/json"]+ * @param contentType+ */+export function isApplicationJSONType(contentType: string | string[]): boolean {+ if (Array.isArray(contentType)) {+ return contentType.some((type) => type.includes(ApplicationJSONType));+ }+ return contentType.includes(ApplicationJSONType);+}+/*** It wraps headers of HTTP requests' and responses' headers.*/@@ -54,14 +66,18 @@ export class HTTPHeaders {this._setHeader(key, value);}- toHeadersInit(): HeadersInit {+ toHeadersInit(body?: any): HeadersInit {const headers: HeadersInit = {};this._headers.forEach((values, key) => {headers[key] = values.join(',');});headers.accept ??= 'application/json, text/plain, */*';- headers['content-type'] ??= 'application/json;charset=UTF-8';++ // If the request body is FormData, the browser will automatically generate Content Type with boundary+ if (!(body instanceof FormData)) {+ headers['content-type'] ??= 'application/json;charset=UTF-8';+ }return headers;}diff --git a/packages/network/src/services/http/request.ts b/packages/network/src/services/http/request.tsindex 5ae3064da7..d5b2821997 100644--- a/packages/network/src/services/http/request.ts+++ b/packages/network/src/services/http/request.ts@@ -17,7 +17,7 @@import type { HTTPHeaders } from './headers';import type { HTTPResponseType } from './http';import type { HTTPParams } from './params';-import { ApplicationJSONType } from './headers';+import { ApplicationJSONType, isApplicationJSONType } from './headers';export type HTTPRequestMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';@@ -62,10 +62,15 @@ export class HTTPRequest {return `${this.url}${this.url.includes('?') ? '&' : '?'}${params}`;}- getBody(): string | null {+ getBody(): string | FormData | null {const contentType = this.headers.get('Content-Type') ?? ApplicationJSONType;const body = this.requestParams?.body;- if (contentType === ApplicationJSONType && body && typeof body === 'object') {++ if (body instanceof FormData) {+ return body;+ }++ if (isApplicationJSONType(contentType) && body && typeof body === 'object') {return JSON.stringify(body);}@@ -73,7 +78,7 @@ export class HTTPRequest {}getHeadersInit(): HeadersInit {- const headersInit = this.headers.toHeadersInit();+ const headersInit = this.headers.toHeadersInit(this.requestParams?.body);return headersInit;}}