Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

Enhance onBeforeRequest into onBeforeRequestHandlers for Api class (#65195)

Timofey Kachalovb9df4f2f7e2e
diff --git a/enterprise/frontend/src/embedding-sdk-bundle/store/auth/auth.ts b/enterprise/frontend/src/embedding-sdk-bundle/store/auth/auth.ts
index f4b2693e9d4..cacd866bb76 100644
--- a/enterprise/frontend/src/embedding-sdk-bundle/store/auth/auth.ts
+++ b/enterprise/frontend/src/embedding-sdk-bundle/store/auth/auth.ts
@@ -15,6 +15,7 @@ import { getBuildInfo } from "embedding-sdk-shared/lib/get-build-info";
import { EMBEDDING_SDK_IFRAME_EMBEDDING_CONFIG } from "metabase/embedding-sdk/config";
import api from "metabase/lib/api";
import { createAsyncThunk } from "metabase/lib/redux";
+import { PLUGIN_EMBEDDING_SDK } from "metabase/plugins";
import { refreshSiteSettings } from "metabase/redux/settings";
import { refreshCurrentUser } from "metabase/redux/user";
import { requestSessionTokenFromEmbedJs } from "metabase-enterprise/embedding_iframe_sdk/utils";
@@ -48,17 +49,19 @@ export const initAuth = createAsyncThunk(
// Use existing user session. Do nothing.
} else if (isValidInstanceUrl) {
// SSO setup
- api.onBeforeRequest = async () => {
- const session = await dispatch(
- getOrRefreshSession({
- metabaseInstanceUrl,
- preferredAuthMethod,
- }),
- ).unwrap();
- if (session?.id) {
- api.sessionToken = session.id;
- }
- };
+ PLUGIN_EMBEDDING_SDK.onBeforeRequestHandlers.getOrRefreshSessionHandler =
+ async () => {
+ const session = await dispatch(
+ getOrRefreshSession({
+ metabaseInstanceUrl,
+ preferredAuthMethod,
+ }),
+ ).unwrap();
+ if (session?.id) {
+ api.sessionToken = session.id;
+ }
+ };
+
try {
// verify that the session is actually valid before proceeding
await dispatch(
diff --git a/frontend/src/metabase/entities/containers/EntityListLoader.unit.spec.js b/frontend/src/metabase/entities/containers/EntityListLoader.unit.spec.js
index 1520e2f671e..57be20f0561 100644
--- a/frontend/src/metabase/entities/containers/EntityListLoader.unit.spec.js
+++ b/frontend/src/metabase/entities/containers/EntityListLoader.unit.spec.js
@@ -1,5 +1,7 @@
import "mutationobserver-shim";
+import { waitFor } from "@testing-library/react";
+
import { renderWithProviders } from "__support__/ui";
import { EntityListLoader } from "metabase/entities/containers/rtk-query";
import { Api } from "metabase/lib/api";
@@ -9,7 +11,9 @@ describe("EntityListLoader", () => {
beforeEach(() => {
_makeRequest = Api.prototype._makeRequest;
- Api.prototype._makeRequest = jest.fn().mockReturnValue(Promise.resolve([]));
+ Api.prototype._makeRequest = jest
+ .fn()
+ .mockReturnValue(Promise.resolve({ data: [] }));
});
afterEach(() => {
@@ -17,13 +21,19 @@ describe("EntityListLoader", () => {
});
describe("with entityType of search", () => {
+ const MockComponent = () => <div>Mock Component</div>;
+
it("should handle object entityQuery", async () => {
renderWithProviders(
<EntityListLoader
entityType="search"
entityQuery={{ collection: "foo" }}
+ ComposedComponent={MockComponent}
/>,
);
+ await waitFor(() => {
+ expect(Api.prototype._makeRequest).toHaveBeenCalled();
+ });
expect(
Api.prototype._makeRequest.mock.calls.map((c) => c.slice(0, 2)),
).toEqual([["GET", "/api/collection/foo/items"]]);
@@ -35,8 +45,12 @@ describe("EntityListLoader", () => {
entityType="search"
entityQuery={(state, props) => ({ collection: props.collectionId })}
collectionId="foo"
+ ComposedComponent={MockComponent}
/>,
);
+ await waitFor(() => {
+ expect(Api.prototype._makeRequest).toHaveBeenCalled();
+ });
expect(
Api.prototype._makeRequest.mock.calls.map((c) => c.slice(0, 2)),
).toEqual([["GET", "/api/collection/foo/items"]]);
diff --git a/frontend/src/metabase/lib/api.js b/frontend/src/metabase/lib/api.js
index 5d36d7938d5..b9e87d10b20 100644
--- a/frontend/src/metabase/lib/api.js
+++ b/frontend/src/metabase/lib/api.js
@@ -1,9 +1,11 @@
import EventEmitter from "events";
import querystring from "querystring";
+import { isEmbeddingSdk } from "metabase/embedding-sdk/config";
import { isTest } from "metabase/env";
import { isWithinIframe } from "metabase/lib/dom";
import { delay } from "metabase/lib/promise";
+import { PLUGIN_EMBEDDING_SDK } from "metabase/plugins";
import { IS_EMBED_PREVIEW } from "./embed";
@@ -37,8 +39,6 @@ export class Api extends EventEmitter {
basename = "";
apiKey = "";
sessionToken;
-
- onBeforeRequest;
onResponseError;
/**
@@ -114,7 +114,7 @@ export class Api extends EventEmitter {
return headers;
}
- _makeMethod(method, creatorOptions = {}) {
+ _makeMethod(methodTemplate, creatorOptions = {}) {
return (urlTemplate, methodOptions = {}) => {
if (typeof methodOptions === "function") {
methodOptions = { transformResponse: methodOptions };
@@ -127,12 +127,12 @@ export class Api extends EventEmitter {
};
return async (rawData, invocationOptions = {}) => {
- if (this.onBeforeRequest) {
- await this.onBeforeRequest();
- }
-
- const options = { ...defaultOptions, ...invocationOptions };
- let url = urlTemplate;
+ let { url, method, options } =
+ await this.apiRequestManipulationMiddleware({
+ url: urlTemplate,
+ method: methodTemplate,
+ options: { ...defaultOptions, ...invocationOptions },
+ });
// this will transform arrays to objects with numeric keys
// we shouldn't be using top level-arrays in the API
const data = { ...rawData };
@@ -376,6 +376,79 @@ export class Api extends EventEmitter {
}
});
}
+
+ /**
+ /**
+ * @typedef {{
+ * method: "GET" | "POST";
+ * url: string;
+ * options: {
+ * headers?: Record<string, string>;
+ * hasBody: boolean;
+ * } & Record<string, unknown>;
+ * }} OnBeforeRequestHandlerData
+ *
+ * @typedef {(data: OnBeforeRequestHandlerData) => (Promise<void | OnBeforeRequestHandlerData>)} OnBeforeRequestHandler
+ *
+ * @typedef {{
+ * key: string;
+ * handler: OnBeforeRequestHandler
+ * }} OnBeforeRequestHandlerDescriptor
+ *
+ * @param data {OnBeforeRequestHandlerData}
+ * @return data {Promise<OnBeforeRequestHandlerData>}
+ */
+ async apiRequestManipulationMiddleware(data) {
+ let { method, url, options } = data;
+
+ /**
+ * Handlers order is important.
+ * Handlers are executed in order and each handler uses the data returned by a previous handler.
+ * @type {OnBeforeRequestHandler[]}
+ */
+ const handlers = [];
+
+ if (isEmbeddingSdk()) {
+ if (
+ PLUGIN_EMBEDDING_SDK.onBeforeRequestHandlers.getOrRefreshSessionHandler
+ ) {
+ // A handler that set's `getOrRefreshSession` logic for SDK
+ handlers.push(
+ PLUGIN_EMBEDDING_SDK.onBeforeRequestHandlers
+ .getOrRefreshSessionHandler,
+ );
+ }
+ }
+
+ if (handlers.length) {
+ for (const handler of handlers) {
+ const onBeforeRequestHandlerResult = await handler({
+ method,
+ url,
+ options,
+ });
+
+ if (onBeforeRequestHandlerResult) {
+ if (onBeforeRequestHandlerResult.method) {
+ method = onBeforeRequestHandlerResult.method;
+ }
+
+ if (onBeforeRequestHandlerResult.url) {
+ url = onBeforeRequestHandlerResult.url;
+ }
+
+ if (onBeforeRequestHandlerResult.options) {
+ options = {
+ ...options,
+ ...onBeforeRequestHandlerResult.options,
+ };
+ }
+ }
+ }
+ }
+
+ return { method, url, options };
+ }
}
const instance = new Api();
diff --git a/frontend/src/metabase/lib/api.unit.spec.ts b/frontend/src/metabase/lib/api.unit.spec.ts
new file mode 100644
index 00000000000..43323953cd4
--- /dev/null
+++ b/frontend/src/metabase/lib/api.unit.spec.ts
@@ -0,0 +1,324 @@
+import { Api } from "./api";
+
+type OnBeforeRequestHandlerData = {
+ method: "GET" | "POST" | "PUT" | "DELETE";
+ url: string;
+ options: {
+ headers?: Record<string, string>;
+ hasBody: boolean;
+ } & Record<string, unknown>;
+};
+
+describe("api", () => {
+ describe("apiRequestManipulationMiddleware", () => {
+ let apiInstance: Api;
+
+ beforeEach(() => {
+ apiInstance = new Api();
+ });
+
+ it("should return the original data when there are no handlers", async () => {
+ const inputData = {
+ method: "GET" as const,
+ url: "/api/test",
+ options: { hasBody: false, json: true },
+ };
+
+ const result =
+ await apiInstance.apiRequestManipulationMiddleware(inputData);
+
+ expect(result).toEqual(inputData);
+ });
+
+ it("should return the original data when handler returns void", async () => {
+ const inputData = {
+ method: "POST" as const,
+ url: "/api/test",
+ options: { hasBody: true, json: true, headers: { "X-Test": "value" } },
+ };
+
+ // Mock a handler that returns void
+ const voidHandler = jest.fn().mockResolvedValue(undefined);
+ jest
+ .spyOn(apiInstance as any, "apiRequestManipulationMiddleware")
+ .mockImplementation(async (data) => {
+ await voidHandler(data);
+ return data;
+ });
+
+ const result =
+ await apiInstance.apiRequestManipulationMiddleware(inputData);
+
+ expect(result).toEqual(inputData);
+ expect(voidHandler).toHaveBeenCalledWith(inputData);
+ });
+
+ it("should update only the url when handler returns partial modification", async () => {
+ const inputData = {
+ method: "GET" as const,
+ url: "/api/original",
+ options: { hasBody: false, json: true },
+ };
+
+ const expectedUrl = "/api/modified";
+
+ jest
+ .spyOn(apiInstance as any, "apiRequestManipulationMiddleware")
+ .mockImplementation(async (data) => {
+ // Simulate handler that only modifies URL
+ const typedData = data as OnBeforeRequestHandlerData;
+ return {
+ method: typedData.method,
+ url: expectedUrl,
+ options: typedData.options,
+ };
+ });
+
+ const result =
+ await apiInstance.apiRequestManipulationMiddleware(inputData);
+
+ expect(result).toEqual({
+ method: inputData.method,
+ url: expectedUrl,
+ options: inputData.options,
+ });
+ });
+
+ it("should update method, url, and options when handler returns full modification", async () => {
+ const inputData = {
+ method: "GET" as const,
+ url: "/api/original",
+ options: { hasBody: false, json: true },
+ };
+
+ const modifications = {
+ method: "POST" as const,
+ url: "/api/modified",
+ options: { hasBody: true, json: false, custom: "value" },
+ };
+
+ jest
+ .spyOn(apiInstance as any, "apiRequestManipulationMiddleware")
+ .mockImplementation(async () => modifications);
+
+ const result =
+ await apiInstance.apiRequestManipulationMiddleware(inputData);
+
+ expect(result).toEqual(modifications);
+ });
+
+ it("should merge options properly when handler returns partial options", async () => {
+ const inputData = {
+ method: "POST" as const,
+ url: "/api/test",
+ options: {
+ hasBody: true,
+ json: true,
+ headers: { "X-Original": "value" },
+ retry: true,
+ },
+ };
+
+ const newHeaders = { "X-Modified": "new-value" };
+
+ jest
+ .spyOn(apiInstance as any, "apiRequestManipulationMiddleware")
+ .mockImplementation(async (data) => {
+ const typedData = data as OnBeforeRequestHandlerData;
+ return {
+ method: typedData.method,
+ url: typedData.url,
+ options: {
+ ...typedData.options,
+ headers: { ...typedData.options.headers, ...newHeaders },
+ },
+ };
+ });
+
+ const result =
+ await apiInstance.apiRequestManipulationMiddleware(inputData);
+
+ expect(result.options.headers).toEqual({
+ "X-Original": "value",
+ "X-Modified": "new-value",
+ });
+ expect(result.options.hasBody).toBe(true);
+ expect(result.options.json).toBe(true);
+ expect(result.options.retry).toBe(true);
+ });
+
+ it("should execute multiple handlers in order", async () => {
+ const inputData = {
+ method: "GET" as const,
+ url: "/api/start",
+ options: { hasBody: false, counter: 0 },
+ };
+
+ const executionOrder: number[] = [];
+
+ const handler1 = jest.fn(
+ async (
+ data: OnBeforeRequestHandlerData & { options: { counter: number } },
+ ) => {
+ executionOrder.push(1);
+ return {
+ ...data,
+ url: data.url + "/step1",
+ options: { ...data.options, counter: data.options.counter + 1 },
+ };
+ },
+ );
+
+ const handler2 = jest.fn(
+ async (
+ data: OnBeforeRequestHandlerData & { options: { counter: number } },
+ ) => {
+ executionOrder.push(2);
+ return {
+ ...data,
+ url: data.url + "/step2",
+ options: { ...data.options, counter: data.options.counter + 10 },
+ };
+ },
+ );
+
+ const handler3 = jest.fn(
+ async (
+ data: OnBeforeRequestHandlerData & { options: { counter: number } },
+ ) => {
+ executionOrder.push(3);
+ return {
+ ...data,
+ url: data.url + "/step3",
+ options: { ...data.options, counter: data.options.counter + 100 },
+ };
+ },
+ );
+
+ // Mock the middleware to use our handlers
+ jest
+ .spyOn(apiInstance as any, "apiRequestManipulationMiddleware")
+ .mockImplementation(async (data) => {
+ let currentData = data as OnBeforeRequestHandlerData & {
+ options: { counter: number };
+ };
+ for (const handler of [handler1, handler2, handler3]) {
+ const result = await handler(currentData);
+ if (result) {
+ currentData = result;
+ }
+ }
+ return currentData;
+ });
+
+ const result =
+ await apiInstance.apiRequestManipulationMiddleware(inputData);
+
+ expect(executionOrder).toEqual([1, 2, 3]);
+ expect(result.url).toBe("/api/start/step1/step2/step3");
+ expect(result.options.counter).toBe(111); // 0 + 1 + 10 + 100
+ expect(handler1).toHaveBeenCalledWith(
+ expect.objectContaining({ url: "/api/start" }),
+ );
+ expect(handler2).toHaveBeenCalledWith(
+ expect.objectContaining({ url: "/api/start/step1" }),
+ );
+ expect(handler3).toHaveBeenCalledWith(
+ expect.objectContaining({ url: "/api/start/step1/step2" }),
+ );
+ });
+
+ it("should handle async handlers correctly", async () => {
+ const inputData = {
+ method: "POST" as const,
+ url: "/api/async",
+ options: { hasBody: true, json: true },
+ };
+
+ const asyncHandler = jest.fn(async (data: OnBeforeRequestHandlerData) => {
+ // Simulate async operation
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ return {
+ ...data,
+ url: "/api/async-modified",
+ };
+ });
+
+ jest
+ .spyOn(apiInstance as any, "apiRequestManipulationMiddleware")
+ .mockImplementation(async (data) => {
+ return await asyncHandler(data as OnBeforeRequestHandlerData);
+ });
+
+ const result =
+ await apiInstance.apiRequestManipulationMiddleware(inputData);
+
+ expect(asyncHandler).toHaveBeenCalled();
+ expect(result.url).toBe("/api/async-modified");
+ });
+
+ it("should handle handler that only returns options", async () => {
+ const inputData = {
+ method: "GET" as const,
+ url: "/api/test",
+ options: { hasBody: false },
+ };
+
+ jest
+ .spyOn(apiInstance as any, "apiRequestManipulationMiddleware")
+ .mockImplementation(async (data) => {
+ const typedData = data as OnBeforeRequestHandlerData;
+ return {
+ method: typedData.method,
+ url: typedData.url,
+ options: { ...typedData.options, newOption: "added" },
+ };
+ });
+
+ const result =
+ await apiInstance.apiRequestManipulationMiddleware(inputData);
+
+ expect(result.method).toBe("GET");
+ expect(result.url).toBe("/api/test");
+ expect(result.options).toEqual({ hasBody: false, newOption: "added" });
+ });
+
+ it("should preserve all original options when handler does not modify them", async () => {
+ const complexOptions = {
+ hasBody: true,
+ json: true,
+ headers: { "X-Custom": "header" },
+ retry: true,
+ retryCount: 5,
+ formData: true,
+ noEvent: false,
+ transformResponse: jest.fn(),
+ };
+
+ const inputData = {
+ method: "POST" as const,
+ url: "/api/complex",
+ options: complexOptions,
+ };
+
+ jest
+ .spyOn(apiInstance as any, "apiRequestManipulationMiddleware")
+ .mockImplementation(async (data) => {
+ const typedData = data as OnBeforeRequestHandlerData;
+ return {
+ ...typedData,
+ url: "/api/modified-url",
+ };
+ });
+
+ const result =
+ await apiInstance.apiRequestManipulationMiddleware(inputData);
+
+ expect(result.url).toBe("/api/modified-url");
+ expect(result.options).toEqual(complexOptions);
+ expect(result.options.transformResponse).toBe(
+ complexOptions.transformResponse,
+ );
+ });
+ });
+});
diff --git a/frontend/src/metabase/plugins/index.ts b/frontend/src/metabase/plugins/index.ts
index 7054d66ac27..470a6cafdc1 100644
--- a/frontend/src/metabase/plugins/index.ts
+++ b/frontend/src/metabase/plugins/index.ts
@@ -581,6 +581,9 @@ export interface SimpleDataPickerProps {
export const PLUGIN_EMBEDDING_SDK = {
isEnabled: () => false,
+ onBeforeRequestHandlers: {
+ getOrRefreshSessionHandler: async () => {},
+ },
};
export const PLUGIN_EMBEDDING_IFRAME_SDK = {