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
Remove legacy API client (#76241)
Romeo Van Snickd2ffdf5e3fbb
diff --git a/e2e/test-component/scenarios/embedding-sdk/sdk-bundle-hooks.cy.spec.tsx b/e2e/test-component/scenarios/embedding-sdk/sdk-bundle-hooks.cy.spec.tsxindex 75aa30c6caf..c132fb43214 100644--- a/e2e/test-component/scenarios/embedding-sdk/sdk-bundle-hooks.cy.spec.tsx+++ b/e2e/test-component/scenarios/embedding-sdk/sdk-bundle-hooks.cy.spec.tsx@@ -311,7 +311,7 @@ describe("scenarios > embedding-sdk > sdk-bundle public hooks", () => {actionId: SdkActionId | null;}) => {// Wait for the SDK's auth flow to complete before firing the action —- // otherwise the legacy-client POST goes out without credentials and+ // otherwise the action POST goes out without credentials and// the backend rejects with a 401.const authStatus = useMetabaseAuthStatus();const { execute, result, error, isExecuting } = useAction<{diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/lib/to-action-execute-error.ts b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/lib/to-action-execute-error.tsindex db265a97490..e22d516a4df 100644--- a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/lib/to-action-execute-error.ts+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/lib/to-action-execute-error.ts@@ -5,7 +5,7 @@ import type { ActionExecuteError } from "../types";/*** Adapter at the public-API boundary: takes whatever the underlying network- * client throws (legacy-client's wrapped response body, a native `Error`+ * client throws (`api.request`'s wrapped response body, a native `Error`* from a transport failure, anything else) and produces a clean* `ActionExecuteError`. The public type must NOT leak the internal shape* (`via`, `cause`, `trace`, etc.) — this helper drops it.diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/lib/to-action-execute-error.unit.spec.ts b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/lib/to-action-execute-error.unit.spec.tsindex 254ca65182b..5b81e3c7a41 100644--- a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/lib/to-action-execute-error.unit.spec.ts+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/lib/to-action-execute-error.unit.spec.ts@@ -1,7 +1,7 @@import { toActionExecuteError } from "./to-action-execute-error";describe("toActionExecuteError", () => {- describe("HTTP-shaped input (legacy-client throw)", () => {+ describe("HTTP-shaped input (api.request throw)", () => {it("normalizes a typical 4xx response", () => {const result = toActionExecuteError({status: 403,@@ -37,7 +37,7 @@ describe("toActionExecuteError", () => {trace: ["frame-1", "frame-2"],},isCancelled: false,- // an unrelated top-level field a future legacy-client could add+ // an unrelated top-level field a future api.request could adddiagnostic: "raw",});diff --git a/frontend/src/embedding-sdk-bundle/lib/execute-action.ts b/frontend/src/embedding-sdk-bundle/lib/execute-action.tsindex 3b08c16cf3a..bc8e663a528 100644--- a/frontend/src/embedding-sdk-bundle/lib/execute-action.ts+++ b/frontend/src/embedding-sdk-bundle/lib/execute-action.ts@@ -1,6 +1,12 @@import type { SdkStore } from "embedding-sdk-bundle/store/types";import type { SdkActionId } from "embedding-sdk-bundle/types/action";-import { POST } from "metabase/api/legacy-client";+import { executeAction as executeActionMutation } from "metabase/api/action";+import type {+ BaseEntityId,+ ParametersForActionExecution,+ WritebackActionId,+} from "metabase-types/api";+import { isBaseEntityID } from "metabase-types/api";type ActionParametersPayload = Record<string, unknown>;@@ -10,28 +16,49 @@ export type ExecuteActionParams = {};/**- * Loose response shape from `POST /api/action/:id/execute`. The body varies- * by action kind (created-row / rows-updated / rows-deleted / rows-affected- * / success+counts). Per-kind discrimination happens in the package hook- * via the generated `ActionResult<TAction>` type — this lib stays loose.+ * Loose response shape from the execute-action endpoint. The body varies by+ * action kind (created-row / rows-updated / rows-deleted / rows-affected /+ * success+counts). Per-kind discrimination happens in the package hook via the+ * generated `ActionResult<TAction>` type — this lib stays loose.** HTTP actions are rejected at the backend and never reach this code path.*/export type ExecuteActionResult = Record<string, unknown>;/**- * Triggers a pre-existing Metabase action. The curried `(store) => fn`- * shape mirrors `createDashboard` / `queryQuestion` / `queryMetric` so the- * package hook can read `executeAction(reduxStore)({...})` off- * `window.METABASE_EMBEDDING_SDK_BUNDLE`. The store isn't actually used- * today — the call is a same-origin POST — but the signature is preserved- * for parity with the other bundle utilities.+ * Narrows the SDK's loose `SdkActionId` (which keeps entity ids as a plain+ * string for ergonomics) into the id the endpoint accepts: a numeric action id+ * or a branded `entity_id`. Throws on a string that is neither.+ */+const parseActionId = (+ actionId: SdkActionId,+): WritebackActionId | BaseEntityId => {+ if (typeof actionId === "number" || isBaseEntityID(actionId)) {+ return actionId;+ }+ throw new Error(`Invalid action id: ${actionId}`);+};++/**+ * Triggers a pre-existing Metabase action. The curried `(store) => fn` shape+ * mirrors `createDashboard` / `queryQuestion` / `queryMetric` so the package+ * hook can read `executeAction(reduxStore)({...})` off+ * `window.METABASE_EMBEDDING_SDK_BUNDLE`.*/export const executeAction =- (_reduxStore: SdkStore) =>+ (reduxStore: SdkStore) =>async ({actionId,parameters = {},}: ExecuteActionParams): Promise<ExecuteActionResult> => {- return await POST(`/api/action/${actionId}/execute`)({ parameters });+ return reduxStore+ .dispatch(+ executeActionMutation.initiate({+ id: parseActionId(actionId),+ // Forwarded unchanged: the SDK keeps the parameter bag loose, and the+ // endpoint validates the values server-side.+ parameters: parameters as ParametersForActionExecution,+ }),+ )+ .unwrap();};diff --git a/frontend/src/metabase-types/api/actions.ts b/frontend/src/metabase-types/api/actions.tsindex cbe62d439fb..b5777e292b3 100644--- a/frontend/src/metabase-types/api/actions.ts+++ b/frontend/src/metabase-types/api/actions.ts@@ -213,7 +213,7 @@ export interface GetActionRequest {}export interface ExecuteActionRequest {- id: WritebackActionId;+ id: WritebackActionId | BaseEntityId;parameters: ParametersForActionExecution;}diff --git a/frontend/src/metabase/api/client/client.ts b/frontend/src/metabase/api/client/client.tsindex 6cc9770edaa..75d7deea268 100644--- a/frontend/src/metabase/api/client/client.ts+++ b/frontend/src/metabase/api/client/client.ts@@ -125,23 +125,51 @@ export class ApiClient extends EventEmitter<EventMap> {};}- private async _dispatch(+ /**+ * Send a prepared request: run it over the network (optionally retrying+ * transient transport failures), read and parse the body, emit auth/error+ * events, and throw `{ status, data }` on a non-2xx response. The single+ * attempt lives in `attempt` so `retry` can re-run it.+ */+ private async _send(init: RequestInit,- withRetries: boolean = false,+ withRetries: boolean,): Promise<unknown> {if (!isRequestMethod(init.method)) {throw new Error("Invalid HTTP method");}+ const attempt = async (): Promise<unknown> => {+ const response = await this._fetch(init);++ const { ok, status, body } = await handleResponse(+ response,+ init.rawResponse,+ );++ if (!init.noEvent && (status === 401 || status === 403)) {+ // Strip basename so listeners (app-main.js) see the relative path.+ this.emit(status, relativeUrl(this.basename, init.url));+ }++ if (!ok) {+ const metabaseVersion = response.headers.get("X-Metabase-Version");+ this.emit("responseError", { metabaseVersion });+ throw { status, data: body };+ }++ return body;+ };+try {if (withRetries) {- return await retry(() => this._makeRequest(init), {+ return await retry(attempt, {maxRetries: MAX_RETRIES,shouldRetry: isRetriableError,signal: init.signal,});}- return await this._makeRequest(init);+ return await attempt();} catch (error) {// When the request is aborted, `fetch` rejects with the standard// `DOMException` of name "AbortError". Let it propagate untouched so@@ -187,31 +215,6 @@ export class ApiClient extends EventEmitter<EventMap> {return response;}- private async _makeRequest<RawResponse extends boolean>(- init: RequestInit<RawResponse>,- ): Promise<ResponseFor<RawResponse>> {- const response = await this._fetch(init);-- const { ok, status, body } = await handleResponse(- response,- init.rawResponse,- );-- if (!init.noEvent && (status === 401 || status === 403)) {- // Strip basename so listeners (app-main.js) see the relative path.- const path = relativeUrl(this.basename, init.url);- this.emit(status, path);- }-- if (!ok) {- const metabaseVersion = response.headers.get("X-Metabase-Version");- this.emit("responseError", { metabaseVersion });- throw { status, data: body };- }-- return body as ResponseFor<RawResponse>;- }-/*** Resolve options through the middleware pipeline and assemble a `RequestInit`:* URL (basename + `:tag` substitution), client headers, and body placement.@@ -291,8 +294,8 @@ export class ApiClient extends EventEmitter<EventMap> {* RTK Query entry point with explicit body/params semantics. Reads and parses* the body, throwing `{ status, data }` on a non-2xx response. Pass* `rawResponse: true` to resolve with the raw `Response` instead. Pass- * `retry: true` for the legacy retry-on-transient-failure behavior used by- * the GET/POST helpers; RTK callers leave it off.+ * `retry: true` to retry on transient transport failures (used by+ * fire-and-forget callers like internal analytics); RTK callers leave it off.*/async request<Raw extends boolean = false>(options: {@@ -304,7 +307,7 @@ export class ApiClient extends EventEmitter<EventMap> {} & RequestOptions<Raw>,): Promise<ResponseFor<Raw>> {const init = await this._prepareRequest(options);- return this._dispatch(init, options.retry ?? false) as ResponseFor<Raw>;+ return this._send(init, options.retry ?? false) as ResponseFor<Raw>;}/**@@ -326,81 +329,6 @@ export class ApiClient extends EventEmitter<EventMap> {const init = await this._prepareRequest(options);return this._fetch(init);}-- /**- * Builds a legacy `GET`/`POST`/`PUT`/`DELETE` helper bound to a URL template.- * Legacy callers pack URL `:tag` values and body fields into a single- * `rawData` bag, which flows through middleware as `data` — letting handlers- * like the embed URL override substitute `:tag` tokens from fields that- * morally live in the body. After URL-tag substitution the leftover bag- * becomes the JSON body (POST/PUT) or the querystring (GET/DELETE).- * FormData / URLSearchParams sidestep this and go through as-is.- *- * @deprecated Call `api.request(...)` directly with explicit `body`/`params`.- * TODO: remove once `metabase/services` and the remaining legacy callers- * (see `rg "from .metabase/api/legacy-client.""`) move to `api.request`.- */- private makeMethod(method: RequestMethod, retry: boolean) {- const hasBody = method === "POST" || method === "PUT";- return (urlTemplate: string, methodOptions: RequestOptions = {}) =>- async <Raw extends boolean = false>(- rawData: any = {},- invocationOptions: RequestOptions<Raw> = {},- ): Promise<Raw extends true ? Response : any> => {- const options = { ...methodOptions, ...invocationOptions };- const headers = {- ...methodOptions.headers,- ...invocationOptions.headers,- };-- if (rawData instanceof FormData || rawData instanceof URLSearchParams) {- const resolved = await this._resolveOptions({- url: urlTemplate,- method,- headers,- data: {},- });- // Let the browser set Content-Type with the multipart boundary- // (FormData) or urlencoded charset (URLSearchParams).- delete resolved.headers["Content-Type"];- return this._dispatch(- { ...options, ...resolved, body: rawData },- retry,- ) as any;- }-- const resolved = await this._resolveOptions({- url: urlTemplate,- method,- headers,- data: rawData,- });-- let body: BodyInit | undefined = undefined;- if (hasBody && resolved.method !== "GET") {- // Leftover bag → JSON body. Middleware saw the whole bag, so embed- // URL `:token` etc. were already substituted from it.- body = JSON.stringify(resolved.data);- } else {- // GET (including POST/PUT overridden to GET by middleware) and- // DELETE: leftover bag goes to the querystring. `fetch` rejects- // GET-with-body, so the override POST→GET embed case lands here too- // — matching the old XHR path that silently dropped the body.- appendQueryParameters(resolved.url, resolved.data);- }-- return this._dispatch({ ...options, ...resolved, body }, retry) as any;- };- }-- /** @deprecated Use `api.request({ method: "GET", ... })` instead. */- GET = this.makeMethod("GET", true);- /** @deprecated Use `api.request({ method: "POST", ... })` instead. */- POST = this.makeMethod("POST", true);- /** @deprecated Use `api.request({ method: "PUT", ... })` instead. */- PUT = this.makeMethod("PUT", false);- /** @deprecated Use `api.request({ method: "DELETE", ... })` instead. */- DELETE = this.makeMethod("DELETE", false);}export const api = new ApiClient();diff --git a/frontend/src/metabase/api/legacy-client.ts b/frontend/src/metabase/api/legacy-client.tsdeleted file mode 100644index d0d59fb0e15..00000000000--- a/frontend/src/metabase/api/legacy-client.ts+++ /dev/null@@ -1,11 +0,0 @@-/**- * @deprecated These helpers are a compatibility shim for callers that haven't- * moved to `api.request(...)` yet. New code should call `api.request` directly- * (or the appropriate RTK endpoint). The exports below are scheduled for- * removal once every importer migrates — search `metabase/api/legacy-client`- * to find them.- */-import { api } from "./client";--export { NetworkError, type RequestMethod } from "./client";-export const { GET, POST, PUT, DELETE } = api;diff --git a/frontend/src/metabase/api/legacy-client.unit.spec.ts b/frontend/src/metabase/api/legacy-client.unit.spec.tsdeleted file mode 100644index c0859f319df..00000000000--- a/frontend/src/metabase/api/legacy-client.unit.spec.ts+++ /dev/null@@ -1,95 +0,0 @@-import fetchMock from "fetch-mock";--import { api } from "./client";-import { GET, POST } from "./legacy-client";--describe("legacy-client", () => {- afterEach(() => {- fetchMock.removeRoutes().clearHistory();- api.beforeRequestHandlers = [];- });-- it("substitutes URL :tags from rawData and routes the remainder to the JSON body for POST", async () => {- fetchMock.post("path:/api/card/42/query", { rows: [] });-- await POST("/api/card/:cardId/query")({- cardId: 42,- parameters: ["a"],- ignore_cache: true,- });-- const call = fetchMock.callHistory.lastCall();- expect(call?.url).toMatch(/\/api\/card\/42\/query$/);- expect(call?.url).not.toContain("parameters=");- expect(call?.options?.body).toBe(- JSON.stringify({ parameters: ["a"], ignore_cache: true }),- );- });-- it("substitutes URL :tags from rawData and routes the remainder to the querystring for GET", async () => {- fetchMock.get("path:/api/card/7/params/p/values", { values: [] });-- await GET("/api/card/:cardId/params/:paramId/values")({- cardId: 7,- paramId: "p",- limit: 10,- });-- const call = fetchMock.callHistory.lastCall();- expect(call?.url).toContain("/api/card/7/params/p/values");- expect(call?.url).toContain("limit=10");- expect(call?.options?.body).toBeFalsy();- });-- it("sends FormData bodies as-is and strips Content-Type", async () => {- fetchMock.post("path:/api/table/9/append-csv", { success: true });-- const formData = new FormData();- formData.append("file", new Blob(["a,b\n1,2"]), "x.csv");-- await POST("/api/table/9/append-csv")(formData);-- const call = fetchMock.callHistory.lastCall();- const sentHeaders = call?.options?.headers as- | Record<string, string>- | Headers- | undefined;- const contentType =- sentHeaders instanceof Headers- ? sentHeaders.get("Content-Type")- : sentHeaders?.["Content-Type"];- expect(contentType).toBeFalsy();- });-- it("lets a middleware-overridden URL substitute :tag tokens from any rawData field (embed flow regression)", async () => {- // Regression for the guest-embed flow: legacy `CardApi.query(rawData)` is- // called with `{ token, parameters, ... }`. The embed URL override- // middleware rewrites `/api/card/:cardId/query` to- // `/api/embed/card/:token/query`, and `:token` must be filled from the- // (body-shaped) `token` field of the bag — not just from URL params.- fetchMock.get("path:/api/embed/card/SOME_JWT/query", { rows: [] });-- api.beforeRequestHandlers.push(async (config) => {- if (config.url === "/api/card/:cardId/query") {- return {- ...config,- method: "GET" as const,- url: "/api/embed/card/:token/query",- };- }- return config;- });-- await POST("/api/card/:cardId/query")({- token: "SOME_JWT",- parameters: "[]",- });-- const call = fetchMock.callHistory.lastCall();- expect(call?.url).toMatch(/\/api\/embed\/card\/SOME_JWT\/query/);- // The override-changed method is GET, so leftover bag fields are folded- // into the querystring (a GET request cannot carry a body).- expect(call?.url).toContain("parameters=");- expect(call?.options?.body).toBeFalsy();- });-});diff --git a/frontend/src/metabase/querying/run-query.ts b/frontend/src/metabase/querying/run-query.tsindex b15d0316378..ace44ad6afd 100644--- a/frontend/src/metabase/querying/run-query.ts+++ b/frontend/src/metabase/querying/run-query.ts@@ -108,9 +108,9 @@ export function runAdhocDatasetQuery(}// Dispatches the RTK saved-card query endpoint, picking the card vs. dashcard-// route (and their pivot variants). Guest embeds rely on the legacy-client-// `onBeforeRequest` middleware (which RTK requests still pass through) rewriting-// the card route to `/api/embed/card/:token/query` when `token` is in the body.+// route (and their pivot variants). Guest embeds rely on the `onBeforeRequest`+// middleware (which RTK requests pass through) rewriting the card route to+// `/api/embed/card/:token/query` when `token` is in the body.let savedCardQueryCounter = 0;function runSavedCardQuery(dispatch: Dispatch,@@ -140,9 +140,9 @@ function runSavedCardQuery(// before it hits the server. Mirrors `runAdhocDatasetQuery`._refetchDeps: ++savedCardQueryCounter,// `token` and `cardId` identify the card in mutually exclusive ways, so we- // send only one (mirroring the original services.js behavior). Guest and- // embedded requests carry a `token`: the legacy `onBeforeRequest` middleware- // rewrites the request to the matching `/api/embed/...` route, discarding+ // send only one. Guest and embedded requests carry a `token`: the+ // `onBeforeRequest` middleware rewrites the request to the matching+ // `/api/embed/...` route, discarding// the `:cardId` path segment. Authenticated requests carry a `cardId`.// The casts below are needed because the shared request types require// `cardId`; we keep that contract strict for every other (authenticated)diff --git a/frontend/test/__support__/ui.tsx b/frontend/test/__support__/ui.tsxindex 94e61d06075..c9ca8c89819 100644--- a/frontend/test/__support__/ui.tsx+++ b/frontend/test/__support__/ui.tsx@@ -21,7 +21,7 @@ import _ from "underscore";import { AppColorSchemeProvider } from "metabase/AppColorSchemeProvider";import { AppKBarProvider } from "metabase/AppKBarProvider";import { Api } from "metabase/api";-import { PUT } from "metabase/api/legacy-client";+import { useUpdateSettingMutation } from "metabase/api/settings";import { UndoListing } from "metabase/common/components/UndoListing";import { baseStyle } from "metabase/css/core/base.styled";import { HistoryProvider } from "metabase/history";@@ -241,6 +241,27 @@ const GlobalStylesForTest = () => {return <Global styles={[baseStyle, cssVariables]} />;};+/**+ * Wires `AppColorSchemeProvider` to the `updateSetting` RTK mutation. Kept as a+ * child component so the hook runs inside the store provider rendered by+ * `TestWrapper`.+ */+const TestColorSchemeProvider = ({ children }: React.PropsWithChildren) => {+ const [updateSetting] = useUpdateSettingMutation();+ const handleUpdateColorScheme = useCallback(+ async (value: any) => {+ await updateSetting({ key: "color-scheme", value }).unwrap();+ },+ [updateSetting],+ );++ return (+ <AppColorSchemeProvider onUpdateColorScheme={handleUpdateColorScheme}>+ {children}+ </AppColorSchemeProvider>+ );+};+export function TestWrapper({children,store,@@ -264,10 +285,6 @@ export function TestWrapper({displayTheme?: "light" | "dark";withCssVariables?: boolean;}): JSX.Element {- const handleUpdateColorScheme = useCallback(async (value: any) => {- await PUT("/api/setting/:key")({ key: "color-scheme", value });- }, []);-const [whitelabelColors, setWhitelabelColors] = useState(() =>MetabaseSettings.applicationColors(),);@@ -280,7 +297,7 @@ export function TestWrapper({return (<MetabaseReduxProvider store={store}><MaybeDNDProvider hasDND={withDND}>- <AppColorSchemeProvider onUpdateColorScheme={handleUpdateColorScheme}>+ <TestColorSchemeProvider><OverlayStackProvider><ThemeProviderContext.Provider value={{ withCssVariables }}><ThemeProvider@@ -301,7 +318,7 @@ export function TestWrapper({</ThemeProvider></ThemeProviderContext.Provider></OverlayStackProvider>- </AppColorSchemeProvider>+ </TestColorSchemeProvider></MaybeDNDProvider></MetabaseReduxProvider>);