The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Replace transformResponse with a rawResponse boolean option (#75003)
Romeo Van Snicked34beed0aaf
diff --git a/enterprise/frontend/src/metabase-enterprise/api/content-translation.ts b/enterprise/frontend/src/metabase-enterprise/api/content-translation.tsindex 3d0fa3a5b87..be38f044c1a 100644--- a/enterprise/frontend/src/metabase-enterprise/api/content-translation.ts+++ b/enterprise/frontend/src/metabase-enterprise/api/content-translation.ts@@ -33,8 +33,7 @@ export const contentTranslationApi = EnterpriseApi.injectEndpoints({return {method: "POST",url: contentTranslationEndpoints.uploadDictionary,- body: { formData },- formData: true,+ body: formData,fetch: true,};},diff --git a/enterprise/frontend/src/metabase-enterprise/api/custom-viz-plugin.ts b/enterprise/frontend/src/metabase-enterprise/api/custom-viz-plugin.tsindex dd9878fa6f6..44837f52e70 100644--- a/enterprise/frontend/src/metabase-enterprise/api/custom-viz-plugin.ts+++ b/enterprise/frontend/src/metabase-enterprise/api/custom-viz-plugin.ts@@ -43,8 +43,7 @@ export const customVizPluginApi = EnterpriseApi.injectEndpoints({return {method: "POST",url: "/api/ee/custom-viz-plugin",- body: { formData },- formData: true,+ body: formData,fetch: true,};},@@ -61,8 +60,7 @@ export const customVizPluginApi = EnterpriseApi.injectEndpoints({return {method: "PUT",url: `/api/ee/custom-viz-plugin/${id}/bundle`,- body: { formData },- formData: true,+ body: formData,fetch: true,};},diff --git a/frontend/src/metabase/api/card.ts b/frontend/src/metabase/api/card.tsindex f1f55d77436..a8b134bc01b 100644--- a/frontend/src/metabase/api/card.ts+++ b/frontend/src/metabase/api/card.ts@@ -173,8 +173,7 @@ export const cardApi = Api.injectEndpoints({return {method: "POST",url: "/api/upload/csv",- body: { formData },- formData: true,+ body: formData,fetch: true,};},diff --git a/frontend/src/metabase/api/dataset.ts b/frontend/src/metabase/api/dataset.tsindex e5482b7f68f..2c003097b03 100644--- a/frontend/src/metabase/api/dataset.ts+++ b/frontend/src/metabase/api/dataset.ts@@ -50,18 +50,14 @@ export const datasetApi = Api.injectEndpoints({return {method: "POST",url,- body: { formData },- formData: true,- fetch: true,- transformResponse: ({ response }: { response: Response }) =>- response,+ body: formData,+ rawResponse: true,};}return {method: "GET",url,- fetch: true,- transformResponse: ({ response }: { response: Response }) => response,+ rawResponse: true,};},}),diff --git a/frontend/src/metabase/api/legacy-client.ts b/frontend/src/metabase/api/legacy-client.tsindex bf7a81e210f..dac2250e360 100644--- a/frontend/src/metabase/api/legacy-client.ts+++ b/frontend/src/metabase/api/legacy-client.ts@@ -26,16 +26,16 @@ type RequestOptions = {json: boolean;hasBody: boolean;noEvent: boolean;- transformResponse: (opts: {- body: object;- data?: Record<string, unknown>;- response?: Response;- }) => Response | undefined;+ /**+ * When `true`, resolve with the raw `Response` instead of the parsed body —+ * for callers that read it themselves (binary downloads, map tiles as a+ * blob). Implies the fetch path (XHR has no `Response` object).+ */+ rawResponse?: boolean;headers: Record<string, string>;retry: boolean;retryCount: number;retryDelayIntervals: number[];- formData?: boolean;fetch?: boolean;signal?: AbortSignal;};@@ -44,7 +44,6 @@ const DEFAULT_OPTIONS: RequestOptions = {json: true,hasBody: false,noEvent: false,- transformResponse: ({ body }) => body as Response,headers: {},retry: false,retryCount: MAX_RETRIES,@@ -69,13 +68,7 @@ type ApiMethod = (type MethodCreator = (urlTemplate: string,- methodOptions?:- | Partial<RequestOptions>- | ((opts: {- body: object;- data?: Record<string, unknown>;- response?: Response;- }) => Response | undefined),+ methodOptions?: Partial<RequestOptions>,) => ApiMethod;/**@@ -200,10 +193,6 @@ export class LegacyApi extends EventEmitter<EventMap> {creatorOptions: Partial<RequestOptions> = {},): MethodCreator {return (urlTemplate, methodOptions = {}) => {- if (typeof methodOptions === "function") {- methodOptions = { transformResponse: methodOptions };- }-const defaultOptions: RequestOptions = {...DEFAULT_OPTIONS,...creatorOptions,@@ -238,15 +227,17 @@ export class LegacyApi extends EventEmitter<EventMap> {}}- let body: string | FormData | undefined;+ let body: string | FormData | URLSearchParams | undefined;if (options.hasBody) {- if (rawData instanceof FormData) {- // Pass `FormData` through unwrapped so the browser sets the right- // multipart Content-Type (with boundary). Drops the legacy- // `body: { formData }, formData: true` wrapper shape.+ if (+ rawData instanceof FormData ||+ rawData instanceof URLSearchParams+ ) {+ // Pass `FormData` / `URLSearchParams` bodies straight through so+ // the browser sets the right Content-Type itself (multipart with+ // boundary, or `application/x-www-form-urlencoded`). Replaces the+ // legacy `body: { formData }, formData: true` wrapper shape.body = rawData;- } else if (options.formData) {- body = rawData["formData"] as FormData;} else {body = JSON.stringify(data);}@@ -265,10 +256,11 @@ export class LegacyApi extends EventEmitter<EventMap> {...options.headers,};- // FormData must NOT carry our default `application/json` Content-Type —- // the browser sets the right value (with the multipart boundary). XHR's- // `xhr.send(formData)` honors this too.- if (body instanceof FormData || (options.formData && options.fetch)) {+ // A `FormData` / `URLSearchParams` body must NOT carry our default+ // `application/json` Content-Type — the browser (or XHR's+ // `send(body)`) sets the correct value, with the multipart boundary+ // for `FormData`. Both transports honor this.+ if (body instanceof FormData || body instanceof URLSearchParams) {delete headers["Content-Type"];}@@ -292,7 +284,7 @@ export class LegacyApi extends EventEmitter<EventMap> {method: string,url: string,headers: Record<string, string>,- body: string | FormData | undefined,+ body: string | FormData | URLSearchParams | undefined,data: Record<string, unknown>,options: RequestOptions,): Promise<unknown> {@@ -335,13 +327,14 @@ export class LegacyApi extends EventEmitter<EventMap> {method: string,url: string,headers: Record<string, string>,- body: string | FormData | undefined,+ body: string | FormData | URLSearchParams | undefined,data: Record<string, unknown>,options: RequestOptions,): Promise<unknown> {// this is temporary to not deal with failed cypress tests// we should switch to using fetch in all cases (metabase#28489)- if (isTest || options.fetch) {+ // `rawResponse` also forces fetch — XHR has no `Response` object.+ if (isTest || options.fetch || options.rawResponse) {return this._makeRequestWithFetch(method,url,@@ -366,7 +359,7 @@ export class LegacyApi extends EventEmitter<EventMap> {method: string,url: string,headers: Record<string, string>,- body: string | FormData | undefined,+ body: string | FormData | URLSearchParams | undefined,data: Record<string, unknown>,options: RequestOptions,): Promise<unknown> {@@ -422,12 +415,6 @@ export class LegacyApi extends EventEmitter<EventMap> {}if (status >= 200 && status <= 299) {- if (options.transformResponse) {- responseBody = options.transformResponse({- body: responseBody as Response,- data,- });- }resolve(responseBody);} else {this.emit("responseError", {@@ -466,7 +453,7 @@ export class LegacyApi extends EventEmitter<EventMap> {method: string,url: string,headers: Record<string, string>,- requestBody: string | FormData | undefined,+ requestBody: string | FormData | URLSearchParams | undefined,data: Record<string, unknown>,options: RequestOptions,): Promise<unknown> {@@ -533,14 +520,10 @@ export class LegacyApi extends EventEmitter<EventMap> {}if (status >= 200 && status <= 299) {- if (options.transformResponse) {- body = options.transformResponse({- body: body as Response,- data,- response: unreadResponse,- });- }- return body;+ // `rawResponse` callers (binary downloads, map tiles) want the+ // `Response` object itself rather than the parsed body — return+ // the unread clone so they can `.blob()`/`.arrayBuffer()` it.+ return options.rawResponse ? unreadResponse : body;} else {this.emit("responseError", { body, status, metabaseVersion });diff --git a/frontend/src/metabase/api/legacy-client.unit.spec.ts b/frontend/src/metabase/api/legacy-client.unit.spec.tsindex 5e58396a590..e06a1af1816 100644--- a/frontend/src/metabase/api/legacy-client.unit.spec.ts+++ b/frontend/src/metabase/api/legacy-client.unit.spec.ts@@ -300,9 +300,8 @@ describe("api", () => {headers: { "X-Custom": "header" },retry: true,retryCount: 5,- formData: true,noEvent: false,- transformResponse: jest.fn(),+ rawResponse: true,};const inputData = {@@ -327,9 +326,7 @@ describe("api", () => {expect(result.url).toBe("/api/modified-url");expect(result.options).toEqual(complexOptions);- expect(result.options.transformResponse).toBe(- complexOptions.transformResponse,- );+ expect(result.options.rawResponse).toBe(true);});});@@ -380,4 +377,38 @@ describe("api", () => {expect(result).toEqual({ hello: "world" });});});++ describe("form-encoded requests", () => {+ let apiInstance: LegacyApi;++ beforeEach(() => {+ apiInstance = new LegacyApi();+ });++ afterEach(() => {+ fetchMock.removeRoutes().clearHistory();+ });++ // Regression: a `URLSearchParams` body (e.g. a dataset download) must be+ // passed through verbatim — not JSON-stringified — and must drop our+ // default `application/json` Content-Type so the browser can set+ // `application/x-www-form-urlencoded`. Keeping the JSON header made the+ // backend reject the request with a 400.+ //+ // The Content-Type strip is gated on `body instanceof URLSearchParams`, so+ // this assertion doubles as proof the body reached `fetch` as a real+ // `URLSearchParams` rather than a JSON string.+ it("drops the application/json Content-Type for a URLSearchParams body", async () => {+ fetchMock.post("path:/api/download", { status: 200, body: "" });++ const body = new URLSearchParams();+ body.append("query", JSON.stringify({ foo: "bar" }));++ await apiInstance.POST("/api/download")(body, { rawResponse: true });++ const call = fetchMock.callHistory.lastCall("path:/api/download");+ const headers = new Headers(call?.options?.headers);+ expect(headers.get("Content-Type")).not.toContain("application/json");+ });+ });});diff --git a/frontend/src/metabase/api/query.ts b/frontend/src/metabase/api/query.tsindex a90dda2bb0b..2e03cce4c1b 100644--- a/frontend/src/metabase/api/query.ts+++ b/frontend/src/metabase/api/query.ts@@ -17,18 +17,18 @@ const isAllowedHTTPMethod = (method: any): method is AllowedHTTPMethods => {export const apiQuery: BaseQueryFn = async (args, ctx, extraOptions) => {const method = typeof args === "string" ? "GET" : (args?.method ?? "GET");const url = typeof args === "string" ? args : args.url;- const { noEvent, formData, fetch, transformResponse } = args;+ const { noEvent, fetch, rawResponse } = args;if (!isAllowedHTTPMethod(method)) {return { error: "Invalid HTTP method" };}- // `FormData` bodies are forwarded as-is — spreading would yield an empty- // object (its entries aren't enumerable as keys) and erase the upload. Other- // bodies merge with `params` so a single combined object reaches the legacy- // client (which doesn't separate them).+ // `FormData` / `URLSearchParams` bodies are forwarded as-is — spreading would+ // yield an empty object (their entries aren't enumerable as keys) and erase+ // the body. Other bodies merge with `params` so a single combined object+ // reaches the legacy client (which doesn't separate them).const rawData =- args?.body instanceof FormData+ args?.body instanceof FormData || args?.body instanceof URLSearchParams? args.body: { ...args?.body, ...args?.params };@@ -36,9 +36,8 @@ export const apiQuery: BaseQueryFn = async (args, ctx, extraOptions) => {const response = await api[method](url)(rawData, {signal: ctx.signal,noEvent,- formData,fetch,- transformResponse,+ rawResponse,...extraOptions,});return { data: response };diff --git a/frontend/src/metabase/visualizations/components/LeafletTilePinMap.tsx b/frontend/src/metabase/visualizations/components/LeafletTilePinMap.tsxindex 4bc91ca6a5b..2cd58d12214 100644--- a/frontend/src/metabase/visualizations/components/LeafletTilePinMap.tsx+++ b/frontend/src/metabase/visualizations/components/LeafletTilePinMap.tsx@@ -180,9 +180,8 @@ export class LeafletTilePinMap extends LeafletMap<LeafletTilePinMapProps> {(GET(tileUrl, {- fetch: true,signal: controller.signal,- transformResponse: ({ response }) => response,+ rawResponse: true,})() as Promise<Response>).then((response) => response.blob())