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 `raw` option with `:tag*` URL template syntax (#74891)
Romeo Van Snickba93b7ebfb4c
diff --git a/frontend/src/metabase/api/legacy-client.ts b/frontend/src/metabase/api/legacy-client.tsindex 7d38f9bbb08..50ed3b2efb9 100644--- a/frontend/src/metabase/api/legacy-client.ts+++ b/frontend/src/metabase/api/legacy-client.ts@@ -2,6 +2,7 @@import EventEmitter from "events";import querystring from "querystring";+import { substituteUrlTags } from "metabase/api/utils/substitute-url-tags";import { isEmbeddingSdk } from "metabase/embedding-sdk/config";import { isTest } from "metabase/env";import { PLUGIN_API, PLUGIN_EMBEDDING_SDK } from "metabase/plugins";@@ -30,7 +31,6 @@ type RequestOptions = {data?: Record<string, unknown>;response?: Response;}) => Response | undefined;- raw: Record<string, boolean>;headers: Record<string, string>;retry: boolean;retryCount: number;@@ -46,7 +46,6 @@ const DEFAULT_OPTIONS: RequestOptions = {hasBody: false,noEvent: false,transformResponse: ({ body }) => body as Response,- raw: {},headers: {},retry: false,retryCount: MAX_RETRIES,@@ -203,19 +202,7 @@ export class LegacyApi extends EventEmitter {...middlewareResult.options,} as RequestOptions;const { data } = middlewareResult;- for (const tag of url.match(/:\w+/g) || []) {- const paramName = tag.slice(1);- let value = data[paramName];- delete data[paramName];- if (value === undefined) {- console.warn("Warning: calling", method, "without", tag);- value = "";- }- if (!options.raw || !options.raw[paramName]) {- value = encodeURIComponent(value as string);- }- url = url.replace(tag, value as string);- }+ url = substituteUrlTags(url, data, method);// remove undefinedfor (const name in data) {if (data[name] === undefined) {diff --git a/frontend/src/metabase/api/utils/index.ts b/frontend/src/metabase/api/utils/index.tsindex 7cca17a11fc..314f44c5581 100644--- a/frontend/src/metabase/api/utils/index.ts+++ b/frontend/src/metabase/api/utils/index.ts@@ -1,4 +1,5 @@export * from "./errors";export * from "./hydrate-legacy-entities";export * from "./settings";+export * from "./substitute-url-tags";export * from "./use-token-refresh";diff --git a/frontend/src/metabase/api/utils/substitute-url-tags.ts b/frontend/src/metabase/api/utils/substitute-url-tags.tsnew file mode 100644index 00000000000..10e0b289106--- /dev/null+++ b/frontend/src/metabase/api/utils/substitute-url-tags.ts@@ -0,0 +1,28 @@+// URL template tags:+// - `:tag` — value is URL-encoded (default; slashes become %2F).+// - `:tag*` — value is substituted raw (slashes preserved), for endpoints+// whose route includes a multi-segment path parameter.+const URL_TAG_REGEX = /:\w+\*?/g;++/**+ * Replace `:tag` / `:tag*` placeholders in a URL template with values pulled+ * from `data`. Substituted keys are deleted from `data` so the caller can use+ * any leftovers as querystring params.+ */+export function substituteUrlTags(+ url: string,+ data: Record<string, unknown>,+ method: string,+): string {+ return url.replace(URL_TAG_REGEX, (tag) => {+ const isRaw = tag.endsWith("*");+ const paramName = tag.slice(1, isRaw ? -1 : undefined);+ const value = data[paramName];+ delete data[paramName];+ if (value === undefined) {+ console.warn("Warning: calling", method, "without", tag);+ return "";+ }+ return isRaw ? String(value) : encodeURIComponent(String(value));+ });+}diff --git a/frontend/src/metabase/api/utils/substitute-url-tags.unit.spec.ts b/frontend/src/metabase/api/utils/substitute-url-tags.unit.spec.tsnew file mode 100644index 00000000000..3f07e2e5f33--- /dev/null+++ b/frontend/src/metabase/api/utils/substitute-url-tags.unit.spec.ts@@ -0,0 +1,71 @@+import { substituteUrlTags } from "./substitute-url-tags";++describe("substituteUrlTags", () => {+ it("returns the URL unchanged when no tags are present", () => {+ const data = { extra: 1 };+ const url = substituteUrlTags("/api/foo", data, "GET");+ expect(url).toBe("/api/foo");+ expect(data).toEqual({ extra: 1 });+ });++ it("substitutes a single :tag and consumes it from data", () => {+ const data = { id: 42, leftover: "x" };+ const url = substituteUrlTags("/api/foo/:id", data, "GET");+ expect(url).toBe("/api/foo/42");+ expect(data).toEqual({ leftover: "x" });+ });++ it("substitutes multiple :tags in one URL", () => {+ const data = { dashId: 1, paramId: "p" };+ const url = substituteUrlTags(+ "/api/dashboard/:dashId/params/:paramId/values",+ data,+ "GET",+ );+ expect(url).toBe("/api/dashboard/1/params/p/values");+ expect(data).toEqual({});+ });++ it("URL-encodes :tag values by default", () => {+ const data = { id: "a/b c" };+ const url = substituteUrlTags("/api/foo/:id", data, "GET");+ expect(url).toBe("/api/foo/a%2Fb%20c");+ });++ it("substitutes :tag* values raw (preserves slashes)", () => {+ const data = { subPath: "table/3/cell/4" };+ const url = substituteUrlTags(+ "/api/automagic-dashboards/:subPath*",+ data,+ "GET",+ );+ expect(url).toBe("/api/automagic-dashboards/table/3/cell/4");+ expect(data).toEqual({});+ });++ it("mixes :tag (encoded) and :tag* (raw) in the same URL", () => {+ const data = { id: "x/y", path: "a/b/c" };+ const url = substituteUrlTags("/api/:id/sub/:path*", data, "GET");+ expect(url).toBe("/api/x%2Fy/sub/a/b/c");+ });++ it("substitutes empty string and warns when a tag has no value in data", () => {+ const warn = jest.spyOn(console, "warn").mockImplementation(() => {});+ const data = {};+ const url = substituteUrlTags("/api/foo/:missing", data, "POST");+ expect(url).toBe("/api/foo/");+ expect(warn).toHaveBeenCalledWith(+ "Warning: calling",+ "POST",+ "without",+ ":missing",+ );+ warn.mockRestore();+ });++ it("coerces non-string values to strings before encoding", () => {+ const data = { id: 7, flag: true };+ const url = substituteUrlTags("/api/:id/:flag", data, "GET");+ expect(url).toBe("/api/7/true");+ });+});diff --git a/frontend/src/metabase/services.js b/frontend/src/metabase/services.jsindex e4b262c45ba..b77b821e496 100644--- a/frontend/src/metabase/services.js+++ b/frontend/src/metabase/services.js@@ -288,10 +288,8 @@ export const EmbedApi = {};export const AutoApi = {- dashboard: GET("/api/automagic-dashboards/:subPath", {- // this prevents the `subPath` parameter from being URL encoded- raw: { subPath: true },- }),+ // `:subPath*` keeps slashes in subPath unencoded (multi-segment path).+ dashboard: GET("/api/automagic-dashboards/:subPath*"),};export const ParameterApi = {