Skip to content

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

Convert metabase/utils files to TypeScript, part 2 (#72679)

Anderson13f17eab13cd
diff --git a/frontend/src/metabase/collections/utils.ts b/frontend/src/metabase/collections/utils.ts
index 169dd50eeca..4e8c5546efc 100644
--- a/frontend/src/metabase/collections/utils.ts
+++ b/frontend/src/metabase/collections/utils.ts
@@ -39,7 +39,7 @@ export function nonPersonalOrArchivedCollection(
}
export function isRootPersonalCollection(
- collection: Partial<Collection> | CollectionItem,
+ collection: Pick<Collection, "personal_owner_id">,
): boolean {
return typeof collection.personal_owner_id === "number";
}
diff --git a/frontend/src/metabase/utils/card.unit.spec.js b/frontend/src/metabase/utils/card.unit.spec.ts
similarity index 73%
rename from frontend/src/metabase/utils/card.unit.spec.js
rename to frontend/src/metabase/utils/card.unit.spec.ts
index 6628c626583..d6cc5bed920 100644
--- a/frontend/src/metabase/utils/card.unit.spec.js
+++ b/frontend/src/metabase/utils/card.unit.spec.ts
@@ -8,6 +8,12 @@ import {
utf8_to_b64,
utf8_to_b64url,
} from "metabase/utils/encoding";
+import type {
+ Card,
+ StructuredDatasetQuery,
+ UnsavedCard,
+ VisualizationDisplay,
+} from "metabase-types/api";
const CARD_ID = 31;
@@ -19,8 +25,16 @@ const getCard = ({
database = 1,
display = "table",
queryFields = {},
- table = undefined,
-}) => {
+ table,
+}: {
+ newCard?: boolean;
+ hasOriginalCard?: boolean;
+ isNative?: boolean;
+ database?: number;
+ display?: VisualizationDisplay;
+ queryFields?: StructuredDatasetQuery["query"];
+ table?: number;
+} = {}): Card | UnsavedCard => {
const savedCardFields = {
name: "Example Saved Question",
description: "For satisfying your craving for information",
@@ -28,27 +42,26 @@ const getCard = ({
id: CARD_ID,
};
+ const datasetQuery = isNative
+ ? {
+ database,
+ type: "native" as const,
+ native: { query: "SELECT * FROM ORDERS" },
+ }
+ : {
+ database,
+ type: "query" as const,
+ query: {
+ ...(table ? { "source-table": table } : {}),
+ ...queryFields,
+ },
+ };
+
return {
name: null,
- display: display,
+ display,
visualization_settings: {},
- dataset_query: {
- database: database,
- type: isNative ? "native" : "query",
- ...(!isNative
- ? {
- query: {
- ...(table ? { "source-table": table } : {}),
- ...queryFields,
- },
- }
- : {}),
- ...(isNative
- ? {
- native: { query: "SELECT * FROM ORDERS" },
- }
- : {}),
- },
+ dataset_query: datasetQuery,
...(newCard ? {} : savedCardFields),
...(hasOriginalCard ? { original_card_id: CARD_ID } : {}),
};
diff --git a/frontend/src/metabase/utils/dashboard_grid.ts b/frontend/src/metabase/utils/dashboard_grid.ts
index fcef2693d61..251fe29e132 100644
--- a/frontend/src/metabase/utils/dashboard_grid.ts
+++ b/frontend/src/metabase/utils/dashboard_grid.ts
@@ -24,7 +24,7 @@ export const DEFAULT_CARD_SIZE = { width: 4, height: 4 };
export const MIN_ROW_HEIGHT = 40;
-type CardPosition = {
+export type CardPosition = {
col: number;
row: number;
size_x: number;
diff --git a/frontend/src/metabase/utils/dashboard_grid.unit.spec.js b/frontend/src/metabase/utils/dashboard_grid.unit.spec.ts
similarity index 84%
rename from frontend/src/metabase/utils/dashboard_grid.unit.spec.js
rename to frontend/src/metabase/utils/dashboard_grid.unit.spec.ts
index f8a1a498819..33b627de166 100644
--- a/frontend/src/metabase/utils/dashboard_grid.unit.spec.js
+++ b/frontend/src/metabase/utils/dashboard_grid.unit.spec.ts
@@ -1,6 +1,8 @@
+import type { CardPosition } from "metabase/utils/dashboard_grid";
import { getPositionForNewDashCard } from "metabase/utils/dashboard_grid";
-const getPos = (cards) => getPositionForNewDashCard(cards, 2, 2, 6);
+const getPos = (cards: CardPosition[]): CardPosition =>
+ getPositionForNewDashCard(cards, 2, 2, 6);
describe("dashboard_grid", () => {
describe("getPositionForNewDashCard", () => {
@@ -32,6 +34,6 @@ describe("dashboard_grid", () => {
});
// shorthand for creating a position object, default to 2x2
-function pos(col, row, size_x = 2, size_y = 2) {
+function pos(col: number, row: number, size_x = 2, size_y = 2): CardPosition {
return { col, row, size_x, size_y };
}
diff --git a/frontend/src/metabase/utils/dom.unit.spec.js b/frontend/src/metabase/utils/dom.unit.spec.ts
similarity index 100%
rename from frontend/src/metabase/utils/dom.unit.spec.js
rename to frontend/src/metabase/utils/dom.unit.spec.ts
diff --git a/frontend/src/metabase/utils/memoize.unit.spec.js b/frontend/src/metabase/utils/memoize.unit.spec.ts
similarity index 79%
rename from frontend/src/metabase/utils/memoize.unit.spec.js
rename to frontend/src/metabase/utils/memoize.unit.spec.ts
index 4cc00554a21..ec79ecc0e90 100644
--- a/frontend/src/metabase/utils/memoize.unit.spec.js
+++ b/frontend/src/metabase/utils/memoize.unit.spec.ts
@@ -8,7 +8,7 @@ describe("memoize", () => {
return ++x;
}
}
- const foo = memoizeClass("bar")(fooInner);
+ const foo = memoizeClass<fooInner>("bar")(fooInner);
const f = new foo();
expect(f.bar()).toEqual(1);
expect(f.bar()).toEqual(1);
@@ -20,7 +20,7 @@ describe("memoize", () => {
return {};
}
}
- const foo = memoizeClass("bar")(fooInner);
+ const foo = memoizeClass<fooInner>("bar")(fooInner);
const f = new foo();
const x = f.bar();
expect(f.bar()).toEqual(x);
@@ -28,11 +28,11 @@ describe("memoize", () => {
it("should use args in cache key", () => {
class fooInner {
- bar(a, b, c) {
+ bar(a: number, b: number, c: number) {
return a + b + c;
}
}
- const foo = memoizeClass("bar")(fooInner);
+ const foo = memoizeClass<fooInner>("bar")(fooInner);
const f = new foo();
expect(f.bar(1, 2, 3)).toEqual(6);
expect(f.bar(1, 2, 4)).toEqual(7);
@@ -40,11 +40,11 @@ describe("memoize", () => {
it("should allow calling with variable number of args", () => {
class fooInner {
- bar(x) {
+ bar(x?: number) {
return x;
}
}
- const foo = memoizeClass("bar")(fooInner);
+ const foo = memoizeClass<fooInner>("bar")(fooInner);
const f = new foo();
expect(f.bar()).toEqual(undefined);
expect(f.bar(1)).toEqual(1);
@@ -61,7 +61,7 @@ describe("memoize", () => {
return ++x;
}
}
- const foo = memoizeClass("bar", "biz")(fooInner);
+ const foo = memoizeClass<fooInner>("bar", "biz")(fooInner);
const f = new foo();
expect(f.bar()).toEqual(1);
expect(f.bar()).toEqual(1);
diff --git a/frontend/src/metabase/utils/pulse.unit.spec.js b/frontend/src/metabase/utils/pulse.unit.spec.ts
similarity index 50%
rename from frontend/src/metabase/utils/pulse.unit.spec.js
rename to frontend/src/metabase/utils/pulse.unit.spec.ts
index 83c62440a6c..630b51c7058 100644
--- a/frontend/src/metabase/utils/pulse.unit.spec.js
+++ b/frontend/src/metabase/utils/pulse.unit.spec.ts
@@ -1,40 +1,53 @@
+import type { DashboardSubscriptionData } from "metabase/redux/store";
import {
+ type RecipientPickerValue,
getActivePulseParameters,
getPulseParameters,
recipientIsValid,
} from "metabase/utils/pulse";
import MetabaseSettings from "metabase/utils/settings";
+import type { Parameter } from "metabase-types/api";
describe("recipientIsValid", () => {
- let originalDomains;
+ let originalDomains: string | null | undefined;
beforeEach(() => {
originalDomains = MetabaseSettings.get("subscription-allowed-domains");
});
afterEach(() => {
- MetabaseSettings.set("subscription-allowed-domains", originalDomains);
+ MetabaseSettings.set(
+ "subscription-allowed-domains",
+ originalDomains ?? null,
+ );
});
it("should be valid for every metabase user", () => {
- const recipient = { id: 1, email: "[email protected]" };
+ const recipient = {
+ id: 1,
+ email: "[email protected]",
+ };
MetabaseSettings.set("subscription-allowed-domains", "metabase.test");
expect(recipientIsValid(recipient)).toBeTruthy();
});
it("should be valid when approved domains are not set", () => {
- const recipient = { email: "[email protected]" };
+ const recipient: RecipientPickerValue = {
+ email: "[email protected]",
+ };
expect(recipientIsValid(recipient)).toBeTruthy();
});
it("should not be valid for a recipient with another domain", () => {
- const recipient = { email: "[email protected]" };
+ const recipient: RecipientPickerValue = {
+ email: "[email protected]",
+ };
MetabaseSettings.set("subscription-allowed-domains", "metabase.test");
expect(recipientIsValid(recipient)).toBeFalsy();
});
it("should be valid for a recipient with the specified domain", () => {
- const recipient = { email: "[email protected]" };
+ const recipient: RecipientPickerValue = { email: "[email protected]" };
MetabaseSettings.set("subscription-allowed-domains", "metabase.test");
expect(recipientIsValid(recipient)).toBeTruthy();
});
@@ -42,75 +55,91 @@ describe("recipientIsValid", () => {
describe("getPulseParameters", () => {
it("returns a pulse's parameters", () => {
- expect(
- getPulseParameters({
- parameters: [{ id: "foo", value: ["foo"] }],
- }),
- ).toEqual([{ id: "foo", value: ["foo"] }]);
+ const pulse: DashboardSubscriptionData = {
+ cards: [],
+ channels: [],
+ parameters: [
+ { id: "foo", name: "foo", type: "string", slug: "foo", value: ["foo"] },
+ ],
+ };
+ expect(getPulseParameters(pulse)).toEqual([
+ { id: "foo", name: "foo", type: "string", slug: "foo", value: ["foo"] },
+ ]);
});
it("defaults to an empty array", () => {
- expect(getPulseParameters()).toEqual([]);
- expect(getPulseParameters({})).toEqual([]);
+ const pulse: DashboardSubscriptionData = { cards: [], channels: [] };
+ expect(getPulseParameters(pulse)).toEqual([]);
});
});
describe("getActivePulseParameters", () => {
- let pulse;
- let parametersList;
+ let pulse: DashboardSubscriptionData;
+ let parametersList: Parameter[];
+
+ const param = (
+ overrides: Partial<Parameter> & { id: string },
+ ): Parameter => ({
+ name: overrides.id,
+ type: "string",
+ slug: overrides.id,
+ ...overrides,
+ });
beforeEach(() => {
pulse = {
+ cards: [],
+ channels: [],
parameters: [
- { id: "no default value", value: ["foo"] },
- { id: "overridden default value", value: ["baz"] },
- { id: "does not exist", value: ["does not exist"] },
- { id: "null value that should be filtered out", value: null },
- {
+ param({ id: "no default value", value: ["foo"] }),
+ param({ id: "overridden default value", value: ["baz"] }),
+ param({ id: "does not exist", value: ["does not exist"] }),
+ param({ id: "null value that should be filtered out", value: null }),
+ param({
id: "undefined value that should be overridden by default",
value: undefined,
- },
+ }),
],
};
parametersList = [
- { id: "no default value" },
- { id: "unused", value: ["unused"] },
- { id: "foo" },
- { id: "overridden default value", default: ["bar"] },
- { id: "unadded default value", default: [123] },
- {
+ param({ id: "no default value" }),
+ param({ id: "unused", value: ["unused"] }),
+ param({ id: "foo" }),
+ param({ id: "overridden default value", default: ["bar"] }),
+ param({ id: "unadded default value", default: [123] }),
+ param({
id: "null value that should be filtered out",
default: ["not null value"],
- },
- {
+ }),
+ param({
id: "undefined value that should be overridden by default",
default: ["not null value"],
- },
+ }),
];
});
it("should return a list of parameters that are applied to the pulse data", () => {
expect(getActivePulseParameters(pulse, parametersList)).toEqual([
- {
+ expect.objectContaining({
id: "no default value",
value: ["foo"],
- },
- {
+ }),
+ expect.objectContaining({
default: ["bar"],
id: "overridden default value",
value: ["baz"],
- },
- {
+ }),
+ expect.objectContaining({
default: [123],
id: "unadded default value",
value: [123],
- },
- {
+ }),
+ expect.objectContaining({
default: ["not null value"],
id: "undefined value that should be overridden by default",
value: ["not null value"],
- },
+ }),
]);
});
});
diff --git a/frontend/src/metabase/utils/urls.unit.spec.js b/frontend/src/metabase/utils/urls.unit.spec.ts
similarity index 92%
rename from frontend/src/metabase/utils/urls.unit.spec.js
rename to frontend/src/metabase/utils/urls.unit.spec.ts
index 93b2e1a86d1..648caa8cd57 100644
--- a/frontend/src/metabase/utils/urls.unit.spec.js
+++ b/frontend/src/metabase/utils/urls.unit.spec.ts
@@ -12,6 +12,7 @@ import {
modelEditor,
question,
} from "metabase/utils/urls";
+import type { Bookmark, CollectionId } from "metabase-types/api";
describe("urls", () => {
describe("question", () => {
@@ -159,9 +160,13 @@ describe("urls", () => {
});
it("should work with `model: dataset` property", () => {
- expect(model({ id: 1, card_id: 42, model: "dataset", name: "Foo" })).toBe(
- "/model/42-foo",
- );
+ const card = {
+ id: 1,
+ card_id: 42,
+ model: "dataset",
+ name: "Foo",
+ };
+ expect(model(card)).toBe("/model/42-foo");
});
it("should handle object ID", () => {
@@ -213,26 +218,24 @@ describe("urls", () => {
});
it("resolves /root and /users collections", () => {
- expect(collection({ id: "root" })).toBe("/collection/root");
- expect(collection({ id: "users" })).toBe("/collection/users");
+ expect(collection({ id: "root", name: "Root" })).toBe("/collection/root");
+ expect(collection({ id: "users", name: "Users" })).toBe(
+ "/collection/users",
+ );
});
it("should treat `null` ID as a root collection", () => {
- expect(collection({ id: null })).toBe("/collection/root");
+ const col = {
+ id: null,
+ name: "Root",
+ };
+ expect(collection(col)).toBe("/collection/root");
});
it("returns correct url", () => {
expect(collection({ id: 1, name: "First collection" })).toBe(
"/collection/1-first-collection",
);
-
- expect(
- collection({
- id: 1,
- slug: "first_collection",
- name: "First collection",
- }),
- ).toBe("/collection/1-first-collection");
});
it("handles possessives correctly", () => {
@@ -301,19 +304,17 @@ describe("urls", () => {
});
it("returns collection bookmark path", () => {
- expect(
- bookmark({
- id: "collection-8",
- item_id: 8,
- name: "Growth",
- type: "collection",
- }),
- ).toBe("/collection/8-growth");
+ const bm: Pick<Bookmark, "id" | "type" | "card_type" | "name"> = {
+ id: "collection-8",
+ name: "Growth",
+ type: "collection",
+ };
+ expect(bookmark(bm)).toBe("/collection/8-growth");
});
});
describe("extractEntityId", () => {
- const testCases = [
+ const testCases: { slug: string | undefined; id: number | undefined }[] = [
{ slug: "33", id: 33 },
{ slug: "33-", id: 33 },
{ slug: "33-metabase-ga", id: 33 },
@@ -331,7 +332,10 @@ describe("urls", () => {
});
describe("extractCollectionId", () => {
- const testCases = [
+ const testCases: {
+ slug: string | undefined;
+ id: CollectionId | undefined;
+ }[] = [
{ slug: "23", id: 23 },
{ slug: "23-", id: 23 },
{ slug: "23-customer-success", id: 23 },
@@ -349,7 +353,7 @@ describe("urls", () => {
});
describe("isCollectionPath", () => {
- const testCases = [
+ const testCases: { path: string; expected: boolean }[] = [
{ path: "collection/1", expected: true },
{ path: "collection/123", expected: true },
{ path: "/collection/1", expected: true },
@@ -452,7 +456,7 @@ describe("urls", () => {
const { caseName, input, expectedString } = testCase;
const entity = { id: 1, name: input };
- function expectedUrl(path, slug) {
+ function expectedUrl(path: string, slug: string): string {
// If slug is an empty string, we test we don't append `-` char
return slug ? `${path}-${slug}` : path;
}
@@ -466,8 +470,7 @@ describe("urls", () => {
it(`should handle ${caseName} correctly for collection URLs`, () => {
// collection objects have not transliterated slugs separated by underscores
// this makes sure they don't affect the slug builder
- const collectionOwnSlug = entity.name.split(" ").join("_");
- expect(collection({ ...entity, slug: collectionOwnSlug })).toBe(
+ expect(collection({ id: entity.id, name: entity.name })).toBe(
expectedUrl("/collection/1", expectedString),
);
});
diff --git a/frontend/src/metabase/utils/urls/collections.ts b/frontend/src/metabase/utils/urls/collections.ts
index e9890f59110..63bbd3098b4 100644
--- a/frontend/src/metabase/utils/urls/collections.ts
+++ b/frontend/src/metabase/utils/urls/collections.ts
@@ -22,8 +22,8 @@ export const tenantUsersPersonalCollectionsForTenant = (tenantId: number) =>
type Collection = Pick<
BaseCollection,
- "id" | "name" | "originalName" | "personal_owner_id" | "type"
->;
+ "name" | "originalName" | "personal_owner_id" | "type"
+> & { id: CollectionId | null };
function slugifyPersonalCollection(collection: Collection) {
// Current user's personal collection name is replaced with "Your personal collection"
@@ -45,9 +45,7 @@ function slugifyPersonalCollection(collection: Collection) {
return slug;
}
-export function collection(
- collection?: Pick<Collection, "id" | "type" | "name"> | null,
-) {
+export function collection(collection?: Collection | null) {
const isSystemCollection =
!collection || collection.id === null || typeof collection.id === "string";