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 entity framework π (#74896)
Romeo Van Snick2ed4929758b0
diff --git a/enterprise/frontend/src/embedding/data-picker/DataSelector/DataSelector.jsx b/enterprise/frontend/src/embedding/data-picker/DataSelector/DataSelector.jsxindex 2ae59f53fbd..28f9cfc8ea6 100644--- a/enterprise/frontend/src/embedding/data-picker/DataSelector/DataSelector.jsx+++ b/enterprise/frontend/src/embedding/data-picker/DataSelector/DataSelector.jsx@@ -12,10 +12,10 @@ import {useListDatabasesQuery,useSearchQuery,} from "metabase/api";+import { runRtkEndpoint } from "metabase/api/utils/run-rtk-endpoint";import { EmptyState } from "metabase/common/components/EmptyState";import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";import CS from "metabase/css/core/index.css";-import { entityCompatibleQuery } from "metabase/entities/utils";import { connect } from "metabase/redux";import { fetchTableMetadata } from "metabase/redux/tables";import { getMetadata } from "metabase/selectors/metadata";@@ -964,7 +964,7 @@ const DataSelector = _.compose(},(dispatch) => ({fetchDatabases: () =>- entityCompatibleQuery(+ runRtkEndpoint({ saved: true },dispatch,databaseApi.endpoints.listDatabases,@@ -972,7 +972,7 @@ const DataSelector = _.compose(),fetchFields: (tableId) => dispatch(fetchTableMetadata({ id: tableId })),fetchQuestion: (id) =>- entityCompatibleQuery(+ runRtkEndpoint({ id: getQuestionIdFromVirtualTableId(id) },dispatch,cardApi.endpoints.getCard,diff --git a/frontend/src/metabase-lib/v1/metadata/Metadata.ts b/frontend/src/metabase-lib/v1/metadata/Metadata.tsindex 0816b0055c4..d106d6d0fbd 100644--- a/frontend/src/metabase-lib/v1/metadata/Metadata.ts+++ b/frontend/src/metabase-lib/v1/metadata/Metadata.ts@@ -24,7 +24,6 @@ import type Field from "./Field";import type Schema from "./Schema";import type Table from "./Table";import { getUniqueFieldId } from "./utils/fields";-import { SAVED_QUESTIONS_VIRTUAL_DB_ID } from "./utils/saved-questions";interface MetadataOpts {databases?: Record<string, Database>;@@ -74,13 +73,6 @@ class Metadata {.value();}- /**- * @deprecated load data via RTK Query - useListDatabaseSchemaTablesQuery- */- tablesList(): Table[] {- return Object.values(this.tables);- }-/*** @deprecated load data via RTK Query - useListFieldsQuery*/@@ -88,13 +80,6 @@ class Metadata {return Object.values(this.fields);}- /**- * @deprecated load data via RTK Query - useListMeasuresQuery- */- measuresList(): Measure[] {- return Object.values(this.measures);- }-/*** @deprecated load data via RTK Query - useGetMeasureQuery*/@@ -109,13 +94,6 @@ class Metadata {return (databaseId != null && this.databases[databaseId]) || null;}- /**- * @deprecated load data via RTK Query - useListDatabasesQuery({ saved: true })- */- savedQuestionsDatabase() {- return this.databases[SAVED_QUESTIONS_VIRTUAL_DB_ID];- }-/*** @deprecated load data via RTK Query - useListSchemasQuery or useListDatabaseSchemaTablesQuery*/diff --git a/frontend/src/metabase-lib/v1/metadata/Metadata.unit.spec.ts b/frontend/src/metabase-lib/v1/metadata/Metadata.unit.spec.tsindex cb5923d20fa..de1e4909bac 100644--- a/frontend/src/metabase-lib/v1/metadata/Metadata.unit.spec.ts+++ b/frontend/src/metabase-lib/v1/metadata/Metadata.unit.spec.ts@@ -1,9 +1,5 @@import { createMockMetadata } from "__support__/metadata";-import {- createMockDatabase,- createMockField,- createMockTable,-} from "metabase-types/api/mocks";+import { createMockDatabase, createMockField } from "metabase-types/api/mocks";describe("Metadata", () => {describe("instantiation", () => {@@ -56,17 +52,6 @@ describe("Metadata", () => {});});- describe("tablesList (deprecated)", () => {- it("should return a list of table objects found on the instance", () => {- const metadata = createMockMetadata({- tables: [createMockTable({ id: 1 }), createMockTable({ id: 2 })],- });-- const tables = metadata.tablesList();- expect(tables).toEqual([metadata.table(1), metadata.table(2)]);- });- });-describe("`field`", () => {it("should return null when given a nil fieldId arg", () => {const metadata = createMockMetadata({});diff --git a/frontend/src/metabase/admin/databases/database.ts b/frontend/src/metabase/admin/databases/database.tsindex 31568cc1201..95e99eec610 100644--- a/frontend/src/metabase/admin/databases/database.ts+++ b/frontend/src/metabase/admin/databases/database.ts@@ -2,7 +2,7 @@ import { createAction, createReducer } from "@reduxjs/toolkit";import { push } from "react-router-redux";import { databaseApi } from "metabase/api";-import { entityCompatibleQuery } from "metabase/entities/utils";+import { runRtkEndpoint } from "metabase/api/utils/run-rtk-endpoint";import { combineReducers } from "metabase/redux";import { createDatabase } from "metabase/redux/databases";import { updateMetadata } from "metabase/redux/metadata-typed";@@ -23,7 +23,7 @@ const DELETE_DATABASE_FAILED = createAction<{export const updateDatabase = function (database: DatabaseData) {return async function (dispatch: Dispatch) {- const result = await entityCompatibleQuery(+ const result = await runRtkEndpoint(database,dispatch,databaseApi.endpoints.updateDatabase,@@ -48,7 +48,7 @@ export const deleteDatabase = function (databaseId: DatabaseId) {return async function (dispatch: Dispatch) {try {dispatch(DELETE_DATABASE_STARTED({ databaseId }));- await entityCompatibleQuery(+ await runRtkEndpoint(databaseId,dispatch,databaseApi.endpoints.deleteDatabase,diff --git a/frontend/src/metabase/admin/permissions/permissions.ts b/frontend/src/metabase/admin/permissions/permissions.tsindex 7d403cc4121..1be35967675 100644--- a/frontend/src/metabase/admin/permissions/permissions.ts+++ b/frontend/src/metabase/admin/permissions/permissions.ts@@ -21,7 +21,7 @@ import {import { getGroupFocusPermissionsUrl } from "metabase/admin/permissions/utils/urls";import { databaseApi, permissionApi } from "metabase/api";import { type ErrorPayload, getErrorMessage } from "metabase/api/utils/errors";-import { entityCompatibleQuery } from "metabase/entities/utils";+import { runRtkEndpoint } from "metabase/api/utils/run-rtk-endpoint";import {PLUGIN_ADVANCED_PERMISSIONS,PLUGIN_DATA_PERMISSIONS,@@ -221,7 +221,7 @@ export const updateDataPermission = createThunkAction(// the reducer below reads the current snapshot synchronously. Swallow// rejections so a failed fetch doesn't surface as an unhandled// promise rejection.- void entityCompatibleQuery(+ void runRtkEndpoint({id: entityId.databaseId,include_hidden: true,diff --git a/frontend/src/metabase/api/card.ts b/frontend/src/metabase/api/card.tsindex 611e1773e5f..f1f55d77436 100644--- a/frontend/src/metabase/api/card.ts+++ b/frontend/src/metabase/api/card.ts@@ -34,7 +34,7 @@ import {provideCardTags,provideParameterValuesTags,} from "./tags";-import { hydrateLegacyEntities } from "./utils/hydrate-legacy-entities";+import { hydrateMetadataStore } from "./utils/hydrate-metadata-store";const PERSISTED_MODEL_REFRESH_DELAY = 200;@@ -78,7 +78,7 @@ export const cardApi = Api.injectEndpoints({params,}),providesTags: (cards = []) => provideCardListTags(cards),- onQueryStarted: hydrateLegacyEntities([QuestionSchema]),+ onQueryStarted: hydrateMetadataStore([QuestionSchema]),}),getCard: builder.query<Card, GetCardRequest>({query: ({ id, ignore_error, ...params }) => ({@@ -88,7 +88,7 @@ export const cardApi = Api.injectEndpoints({noEvent: ignore_error,}),providesTags: (card) => (card ? provideCardTags(card) : []),- onQueryStarted: hydrateLegacyEntities(QuestionSchema),+ onQueryStarted: hydrateMetadataStore(QuestionSchema),}),getCardQueryMetadata: builder.query<CardQueryMetadata, CardId>({query: (id) => ({@@ -97,7 +97,7 @@ export const cardApi = Api.injectEndpoints({}),providesTags: (metadata, _error, id) =>metadata ? provideCardQueryMetadataTags(id, metadata) : [],- onQueryStarted: hydrateLegacyEntities(QueryMetadataSchema),+ onQueryStarted: hydrateMetadataStore(QueryMetadataSchema),}),getCardQuery: builder.query<Dataset, CardQueryRequest>({query: ({ cardId, ...body }) => ({diff --git a/frontend/src/metabase/api/collection.ts b/frontend/src/metabase/api/collection.tsindex e04e1b259d1..d28a72478a7 100644--- a/frontend/src/metabase/api/collection.ts+++ b/frontend/src/metabase/api/collection.ts@@ -28,7 +28,7 @@ import {provideCollectionListTags,provideCollectionTags,} from "./tags";-import { hydrateLegacyEntities } from "./utils/hydrate-legacy-entities";+import { hydrateMetadataStore } from "./utils/hydrate-metadata-store";const flattenCollectionTree = (tree: Collection[]): Collection[] =>tree.flatMap((collection) => [@@ -62,7 +62,7 @@ export const collectionApi = Api.injectEndpoints({providesTags: (collections = []) =>provideCollectionListTags(collections),onQueryStarted: (request, lifecycle) =>- hydrateLegacyEntities([collectionSchemaForRequest(request)])(+ hydrateMetadataStore([collectionSchemaForRequest(request)])(request,lifecycle,),@@ -82,7 +82,7 @@ export const collectionApi = Api.injectEndpoints({"collection-tree",],onQueryStarted: (request, lifecycle) =>- hydrateLegacyEntities<Collection[]>(+ hydrateMetadataStore<Collection[]>([collectionSchemaForRequest(request)],flattenCollectionTree,)(request, lifecycle),@@ -100,7 +100,7 @@ export const collectionApi = Api.injectEndpoints({...provideCollectionItemListTags(response?.data ?? [], models),{ type: "collection", id: `${id}-items` },],- onQueryStarted: hydrateLegacyEntities<ListCollectionItemsResponse>(+ onQueryStarted: hydrateMetadataStore<ListCollectionItemsResponse>([ObjectUnionSchema],(response) => response.data,),@@ -117,7 +117,7 @@ export const collectionApi = Api.injectEndpoints({providesTags: (collection) =>collection ? provideCollectionTags(collection) : [],onQueryStarted: (request, lifecycle) =>- hydrateLegacyEntities(collectionSchemaForRequest(request))(+ hydrateMetadataStore(collectionSchemaForRequest(request))(request,lifecycle,),diff --git a/frontend/src/metabase/api/dashboard.ts b/frontend/src/metabase/api/dashboard.tsindex dedf6010de8..6ea68a2c658 100644--- a/frontend/src/metabase/api/dashboard.ts+++ b/frontend/src/metabase/api/dashboard.ts@@ -35,7 +35,7 @@ import {provideValidDashboardFilterFieldTags,tag,} from "./tags";-import { hydrateLegacyEntities } from "./utils/hydrate-legacy-entities";+import { hydrateMetadataStore } from "./utils/hydrate-metadata-store";export const dashboardApi = Api.injectEndpoints({endpoints: (builder) => {@@ -70,7 +70,7 @@ export const dashboardApi = Api.injectEndpoints({}),providesTags: (dashboards) =>dashboards ? provideDashboardListTags(dashboards) : [],- onQueryStarted: hydrateLegacyEntities([DashboardSchema]),+ onQueryStarted: hydrateMetadataStore([DashboardSchema]),}),getDashboard: builder.query<Dashboard, GetDashboardRequest>({query: ({ id, ignore_error }) => ({@@ -80,7 +80,7 @@ export const dashboardApi = Api.injectEndpoints({}),providesTags: (dashboard) =>dashboard ? provideDashboardTags(dashboard) : [],- onQueryStarted: hydrateLegacyEntities(DashboardSchema),+ onQueryStarted: hydrateMetadataStore(DashboardSchema),}),getDashboardQueryMetadata: builder.query<DashboardQueryMetadata,@@ -93,7 +93,7 @@ export const dashboardApi = Api.injectEndpoints({}),providesTags: (metadata) =>metadata ? provideDashboardQueryMetadataTags(metadata) : [],- onQueryStarted: hydrateLegacyEntities(QueryMetadataSchema),+ onQueryStarted: hydrateMetadataStore(QueryMetadataSchema),}),getRemappedDashboardParameterValue: builder.query<FieldValue,diff --git a/frontend/src/metabase/api/measure.ts b/frontend/src/metabase/api/measure.tsindex 0f88f0b66a9..588ba7aef43 100644--- a/frontend/src/metabase/api/measure.ts+++ b/frontend/src/metabase/api/measure.ts@@ -21,7 +21,7 @@ import {provideMeasureTags,tag,} from "./tags";-import { hydrateLegacyEntities } from "./utils/hydrate-legacy-entities";+import { hydrateMetadataStore } from "./utils/hydrate-metadata-store";export const measureApi = Api.injectEndpoints({endpoints: (builder) => ({@@ -31,7 +31,7 @@ export const measureApi = Api.injectEndpoints({url: "/api/measure",}),providesTags: (measures = []) => provideMeasureListTags(measures),- onQueryStarted: hydrateLegacyEntities([MeasureSchema]),+ onQueryStarted: hydrateMetadataStore([MeasureSchema]),}),getMeasure: builder.query<Measure, MeasureId>({query: (id) => ({@@ -39,7 +39,7 @@ export const measureApi = Api.injectEndpoints({url: `/api/measure/${id}`,}),providesTags: (measure) => (measure ? provideMeasureTags(measure) : []),- onQueryStarted: hydrateLegacyEntities(MeasureSchema),+ onQueryStarted: hydrateMetadataStore(MeasureSchema),}),getMeasureDimensionValues: builder.query<GetMeasureDimensionValuesResponse,diff --git a/frontend/src/metabase/api/metric.ts b/frontend/src/metabase/api/metric.tsindex 9eb2ddbd7ef..b3bc1225a73 100644--- a/frontend/src/metabase/api/metric.ts+++ b/frontend/src/metabase/api/metric.ts@@ -19,7 +19,7 @@ import {provideMetricListTags,provideMetricTags,} from "./tags/utils";-import { hydrateLegacyEntities } from "./utils/hydrate-legacy-entities";+import { hydrateMetadataStore } from "./utils/hydrate-metadata-store";export const metricApi = Api.injectEndpoints({endpoints: (builder) => ({@@ -29,7 +29,7 @@ export const metricApi = Api.injectEndpoints({url: "/api/metric",}),providesTags: (metrics = []) => provideMetricListTags(metrics),- onQueryStarted: hydrateLegacyEntities([MetricSchema]),+ onQueryStarted: hydrateMetadataStore([MetricSchema]),}),getMetric: builder.query<Metric, MetricId>({query: (id) => ({@@ -37,7 +37,7 @@ export const metricApi = Api.injectEndpoints({url: `/api/metric/${id}`,}),providesTags: (metric) => (metric ? provideMetricTags(metric) : []),- onQueryStarted: hydrateLegacyEntities(MetricSchema),+ onQueryStarted: hydrateMetadataStore(MetricSchema),}),getMetricDimensionValues: builder.query<GetMetricDimensionValuesResponse,diff --git a/frontend/src/metabase/api/segment.ts b/frontend/src/metabase/api/segment.tsindex 386b7f40e1b..b1be4f7df6a 100644--- a/frontend/src/metabase/api/segment.ts+++ b/frontend/src/metabase/api/segment.ts@@ -15,7 +15,7 @@ import {provideSegmentTags,tag,} from "./tags";-import { hydrateLegacyEntities } from "./utils/hydrate-legacy-entities";+import { hydrateMetadataStore } from "./utils/hydrate-metadata-store";export const segmentApi = Api.injectEndpoints({endpoints: (builder) => ({@@ -25,7 +25,7 @@ export const segmentApi = Api.injectEndpoints({url: "/api/segment",}),providesTags: (segments = []) => provideSegmentListTags(segments),- onQueryStarted: hydrateLegacyEntities([SegmentSchema]),+ onQueryStarted: hydrateMetadataStore([SegmentSchema]),}),getSegment: builder.query<Segment, SegmentId>({query: (id) => ({@@ -33,7 +33,7 @@ export const segmentApi = Api.injectEndpoints({url: `/api/segment/${id}`,}),providesTags: (segment) => (segment ? provideSegmentTags(segment) : []),- onQueryStarted: hydrateLegacyEntities(SegmentSchema),+ onQueryStarted: hydrateMetadataStore(SegmentSchema),}),createSegment: builder.mutation<Segment, CreateSegmentRequest>({query: (body) => ({diff --git a/frontend/src/metabase/api/snippet.ts b/frontend/src/metabase/api/snippet.tsindex 80d00566052..40870c607e3 100644--- a/frontend/src/metabase/api/snippet.ts+++ b/frontend/src/metabase/api/snippet.ts@@ -15,7 +15,7 @@ import {provideSnippetListTags,provideSnippetTags,} from "./tags";-import { hydrateLegacyEntities } from "./utils/hydrate-legacy-entities";+import { hydrateMetadataStore } from "./utils/hydrate-metadata-store";export const snippetApi = Api.injectEndpoints({endpoints: (builder) => ({@@ -29,7 +29,7 @@ export const snippetApi = Api.injectEndpoints({params,}),providesTags: (snippets = []) => provideSnippetListTags(snippets),- onQueryStarted: hydrateLegacyEntities([SnippetSchema]),+ onQueryStarted: hydrateMetadataStore([SnippetSchema]),}),getSnippet: builder.query<NativeQuerySnippet, NativeQuerySnippetId>({query: (id) => ({@@ -37,7 +37,7 @@ export const snippetApi = Api.injectEndpoints({url: `/api/native-query-snippet/${id}`,}),providesTags: (snippet) => (snippet ? provideSnippetTags(snippet) : []),- onQueryStarted: hydrateLegacyEntities(SnippetSchema),+ onQueryStarted: hydrateMetadataStore(SnippetSchema),}),createSnippet: builder.mutation<NativeQuerySnippet, CreateSnippetRequest>({query: (body) => ({@@ -47,7 +47,7 @@ export const snippetApi = Api.injectEndpoints({}),invalidatesTags: (_, error) =>invalidateTags(error, [listTag("snippet")]),- onQueryStarted: hydrateLegacyEntities(SnippetSchema),+ onQueryStarted: hydrateMetadataStore(SnippetSchema),}),updateSnippet: builder.mutation<NativeQuerySnippet, UpdateSnippetRequest>({query: ({ id, ...body }) => ({@@ -57,7 +57,7 @@ export const snippetApi = Api.injectEndpoints({}),invalidatesTags: (_, error, { id }) =>invalidateTags(error, [listTag("snippet"), idTag("snippet", id)]),- onQueryStarted: hydrateLegacyEntities(SnippetSchema),+ onQueryStarted: hydrateMetadataStore(SnippetSchema),}),}),});diff --git a/frontend/src/metabase/entities/containers/rtk-query/types/rtk.ts b/frontend/src/metabase/api/types/rtk.tssimilarity index 100%rename from frontend/src/metabase/entities/containers/rtk-query/types/rtk.tsrename to frontend/src/metabase/api/types/rtk.tsdiff --git a/frontend/src/metabase/api/utils/hydrate-legacy-entities.ts b/frontend/src/metabase/api/utils/hydrate-metadata-store.tssimilarity index 51%rename from frontend/src/metabase/api/utils/hydrate-legacy-entities.tsrename to frontend/src/metabase/api/utils/hydrate-metadata-store.tsindex 0dfd9ff9bbe..11ae7eed5bf 100644--- a/frontend/src/metabase/api/utils/hydrate-legacy-entities.ts+++ b/frontend/src/metabase/api/utils/hydrate-metadata-store.ts@@ -5,16 +5,16 @@ import { updateMetadata } from "metabase/redux/metadata-typed";import { handleQueryFulfilled } from "./lifecycle";/**- * Bridges RTK Query responses into the entity store.+ * `onQueryStarted` helper that mirrors an RTK Query response into the+ * normalized `state.entities.<slice>` store via `metabase/entities/UPDATE`.*- * Legacy code paths still in use, ie. notably `Entity.actions.update`,- * which reads the original object via `getObject` to build undo payloads- * require those slices to be hydrated.- *- * TODO: Delete this helper, and remove every call site, when the legacy entity- * system is gone.+ * Why this exists: `getMetadata` in `metabase/selectors/metadata.ts` (and the+ * `Metadata`/`Database`/`Table`/β¦ wrappers it builds) read directly from+ * `state.entities.*`, stitching one logical object together from several+ * endpoints' payloads. Every endpoint whose payload should flow into+ * `getMetadata` therefore needs to hydrate the slices on each successful fetch.*/-export const hydrateLegacyEntities =+export const hydrateMetadataStore =<Response>(schema: Schema,pick: (response: Response) => unknown = (response) => response,diff --git a/frontend/src/metabase/api/utils/index.ts b/frontend/src/metabase/api/utils/index.tsindex 314f44c5581..3c6ad8edd7f 100644--- a/frontend/src/metabase/api/utils/index.ts+++ b/frontend/src/metabase/api/utils/index.ts@@ -1,5 +1,6 @@export * from "./errors";-export * from "./hydrate-legacy-entities";+export * from "./hydrate-metadata-store";+export * from "./run-rtk-endpoint";export * from "./settings";export * from "./substitute-url-tags";export * from "./use-token-refresh";diff --git a/frontend/src/metabase/api/utils/run-rtk-endpoint.ts b/frontend/src/metabase/api/utils/run-rtk-endpoint.tsnew file mode 100644index 00000000000..5a2a03eb814--- /dev/null+++ b/frontend/src/metabase/api/utils/run-rtk-endpoint.ts@@ -0,0 +1,29 @@+/**+ * Structural minimum of an RTK Query endpoint descriptor. Concrete endpoints from+ * RTK Query carry many extra properties (hooks, selectors, etc.) and concrete+ * argument/result types β we only rely on `initiate` here.+ */+type RTKEndpoint = { initiate: (request: any, options: any) => any };++type AnyDispatch = (action: any) => any;++/**+ * Imperatively dispatch an RTK Query endpoint, await its result, and clean up+ * the subscription. Use this when you need an endpoint's data inside a thunk+ * or other non-component code path, where the `useFooQuery` hook isn't an+ * option.+ */+export async function runRtkEndpoint(+ request: unknown,+ dispatch: AnyDispatch,+ endpoint: RTKEndpoint,+ { forceRefetch = true } = {},+): Promise<any> {+ const action = dispatch(endpoint.initiate(request, { forceRefetch }));++ try {+ return await action.unwrap();+ } finally {+ action.unsubscribe?.();+ }+}diff --git a/frontend/src/metabase/collections/components/CollectionCopyEntityModal.tsx b/frontend/src/metabase/collections/components/CollectionCopyEntityModal.tsxindex e0a1f2f7f1b..9b63996e097 100644--- a/frontend/src/metabase/collections/components/CollectionCopyEntityModal.tsx+++ b/frontend/src/metabase/collections/components/CollectionCopyEntityModal.tsx@@ -8,7 +8,7 @@ import {} from "metabase/api";import { useInitialCollectionId } from "metabase/collections/hooks";import EntityCopyModal from "metabase/entities/containers/EntityCopyModal";-import { entityTypeForObject } from "metabase/entities/utils";+import { entityTypeForObject } from "metabase/redux/store/entities";const getTitle = (entityObject: any, isShallowCopy: boolean) => {if (entityObject.model !== "dashboard") {diff --git a/frontend/src/metabase/common/components/ErrorPages/use-error-info.ts b/frontend/src/metabase/common/components/ErrorPages/use-error-info.tsindex 0bf4ea2b3ae..f9a0aeda8ec 100644--- a/frontend/src/metabase/common/components/ErrorPages/use-error-info.ts+++ b/frontend/src/metabase/common/components/ErrorPages/use-error-info.ts@@ -4,7 +4,7 @@ import { t } from "ttag";import { datasetApi } from "metabase/api";import { useLazyGetBugReportDetailsQuery } from "metabase/api/bug-report";import { useLazyListLogsQuery } from "metabase/api/logger";-import { entityCompatibleQuery } from "metabase/entities/utils";+import { runRtkEndpoint } from "metabase/api/utils/run-rtk-endpoint";import { useDispatch, useSelector } from "metabase/redux";import { getUser, getUserIsAdmin } from "metabase/selectors/user";@@ -82,7 +82,7 @@ export const useErrorInfo = (const queryResults =hasQueryData(entity) &&entityInfo?.dataset_query &&- (await entityCompatibleQuery(+ (await runRtkEndpoint(entityInfo.dataset_query,dispatch,datasetApi.endpoints.getAdhocQuery,diff --git a/frontend/src/metabase/dashboard/actions/cards-typed.ts b/frontend/src/metabase/dashboard/actions/cards-typed.tsindex ccd702d3156..3dbc58eecb0 100644--- a/frontend/src/metabase/dashboard/actions/cards-typed.ts+++ b/frontend/src/metabase/dashboard/actions/cards-typed.ts@@ -3,7 +3,7 @@ import { t } from "ttag";import _ from "underscore";import { cardApi } from "metabase/api";-import { entityCompatibleQuery } from "metabase/entities/utils";+import { runRtkEndpoint } from "metabase/api/utils/run-rtk-endpoint";import { loadMetadataForCard } from "metabase/questions/actions";import { createThunkAction } from "metabase/redux";import type { Dispatch, GetState } from "metabase/redux/store";@@ -173,7 +173,7 @@ export type AddCardToDashboardOpts = NewDashCardOpts & {export const addCardToDashboard =({ dashId, tabId, cardId }: AddCardToDashboardOpts) =>async (dispatch: Dispatch) => {- const card = await entityCompatibleQuery(+ const card = await runRtkEndpoint({ id: cardId },dispatch,cardApi.endpoints.getCard,@@ -253,7 +253,7 @@ export const replaceCard =async (dispatch: Dispatch, getState: GetState) => {const dashboardId = getDashboardId(getState());- const card = await entityCompatibleQuery(+ const card = await runRtkEndpoint({ id: nextCardId },dispatch,cardApi.endpoints.getCard,@@ -298,7 +298,7 @@ export const addCardWithVisualization =const cards: Card[] = [];for (const cardId of cardIds) {- const card: Card = await entityCompatibleQuery(+ const card: Card = await runRtkEndpoint({ id: cardId },dispatch,cardApi.endpoints.getCard,@@ -348,7 +348,7 @@ export const replaceCardWithVisualization =const cards: Card[] = [];for (const cardId of cardIds) {- const card: Card = await entityCompatibleQuery(+ const card: Card = await runRtkEndpoint({ id: cardId },dispatch,cardApi.endpoints.getCard,diff --git a/frontend/src/metabase/dashboard/actions/data-fetching.ts b/frontend/src/metabase/dashboard/actions/data-fetching.tsindex 178cc35f32b..5f78f563d49 100644--- a/frontend/src/metabase/dashboard/actions/data-fetching.ts+++ b/frontend/src/metabase/dashboard/actions/data-fetching.ts@@ -5,6 +5,7 @@ import { t } from "ttag";import _ from "underscore";import { automagicDashboardsApi, cardApi, dashboardApi } from "metabase/api";+import { runRtkEndpoint } from "metabase/api/utils/run-rtk-endpoint";import { applyParameters } from "metabase/common/utils/card";import { showAutoApplyFiltersToast } from "metabase/dashboard/actions/parameters";import { DASHBOARD_SLOW_TIMEOUT } from "metabase/dashboard/constants";@@ -24,7 +25,6 @@ import {getAllDashboardCards,getCurrentTabDashboardCards,} from "metabase/dashboard/utils";-import { entityCompatibleQuery } from "metabase/entities/utils";import { getSavedDashboardUiParameters } from "metabase/parameters/utils/dashboards";import { getParameterValuesByIdFromQueryParams } from "metabase/parameters/utils/parameter-parsing";import { updateMetadata } from "metabase/redux/metadata";@@ -764,7 +764,7 @@ export const fetchDashboard = createAsyncThunk({ subPath, dashboard_load_id: dashboardLoadId },{ signal: fetchDashboardCancellation.signal },),- entityCompatibleQuery(+ runRtkEndpoint({entity,entityId,@@ -797,7 +797,7 @@ export const fetchDashboard = createAsyncThunk({ dashId: dashId, dashboard_load_id: dashboardLoadId },{ signal: fetchDashboardCancellation.signal },),- entityCompatibleQuery(+ runRtkEndpoint({ id: dashId, dashboard_load_id: dashboardLoadId },dispatch,dashboardApi.endpoints.getDashboardQueryMetadata,diff --git a/frontend/src/metabase/dashboard/actions/revisions.ts b/frontend/src/metabase/dashboard/actions/revisions.tsindex 07bda754dd3..025aa132823 100644--- a/frontend/src/metabase/dashboard/actions/revisions.ts+++ b/frontend/src/metabase/dashboard/actions/revisions.ts@@ -1,9 +1,9 @@import { revisionApi } from "metabase/api";+import { runRtkEndpoint } from "metabase/api/utils/run-rtk-endpoint";import {fetchDashboard,fetchDashboardCardData,} from "metabase/dashboard/actions";-import { entityCompatibleQuery } from "metabase/entities/utils";import { createThunkAction } from "metabase/redux";import { REVERT_TO_REVISION } from "metabase/redux/dashboard";import type { DashboardId, Revision } from "metabase-types/api";@@ -12,7 +12,7 @@ export const revertToRevision = createThunkAction(REVERT_TO_REVISION,(dashboardId: DashboardId, revision: Revision) => {return async (dispatch) => {- await entityCompatibleQuery(+ await runRtkEndpoint({id: dashboardId,entity: "dashboard",diff --git a/frontend/src/metabase/dashboard/actions/save.ts b/frontend/src/metabase/dashboard/actions/save.tsindex 4eff1d2ae42..8e2b4e3293d 100644--- a/frontend/src/metabase/dashboard/actions/save.ts+++ b/frontend/src/metabase/dashboard/actions/save.ts@@ -2,7 +2,7 @@ import { assocIn, dissocIn, getIn } from "icepick";import _ from "underscore";import { cardApi, dashboardApi } from "metabase/api";-import { entityCompatibleQuery } from "metabase/entities/utils";+import { runRtkEndpoint } from "metabase/api/utils/run-rtk-endpoint";import { clickBehaviorIsValid } from "metabase/parameters/utils/click-behavior";import { createThunkAction } from "metabase/redux";import { UPDATE_DASHBOARD_AND_CARDS } from "metabase/redux/dashboard";@@ -191,7 +191,7 @@ export const updateDashboardAndCards = createThunkAction(.filter((tab) => !tab.isRemoved).map(({ id, name }) => ({ id, name }));- await entityCompatibleQuery(+ await runRtkEndpoint({...dashboard,dashcards: dashcardsToUpdate,@@ -263,7 +263,7 @@ export const updateDashboard = createThunkAction(if (attributeNames.length > 0) {const attributes = _.pick(dashboard, attributeNames);- await entityCompatibleQuery(+ await runRtkEndpoint({ id: dashboardId, ...attributes },dispatch,dashboardApi.endpoints.updateDashboard,diff --git a/frontend/src/metabase/dashboard/actions/trash.ts b/frontend/src/metabase/dashboard/actions/trash.tsindex 6bc96e1b2b8..7e641ece2ee 100644--- a/frontend/src/metabase/dashboard/actions/trash.ts+++ b/frontend/src/metabase/dashboard/actions/trash.ts@@ -2,10 +2,10 @@ import { t } from "ttag";import _ from "underscore";import { cardApi, dashboardApi } from "metabase/api";+import { runRtkEndpoint } from "metabase/api/utils/run-rtk-endpoint";import { getTrashUndoMessage } from "metabase/archive/utils";import { canonicalCollectionId } from "metabase/collections/utils";import { fetchDashboard } from "metabase/dashboard/actions";-import { entityCompatibleQuery } from "metabase/entities/utils";import { createThunkAction } from "metabase/redux";import { addUndo } from "metabase/redux/undo";@@ -22,7 +22,7 @@ export const setArchivedDashboard = createThunkAction(? dashboards[dashboardId]: { name: "Dashboard" };- await entityCompatibleQuery(+ await runRtkEndpoint({ id: dashboardId, archived },dispatch,dashboardApi.endpoints.updateDashboard,@@ -58,7 +58,7 @@ export const setArchivedDashboard = createThunkAction(try {await Promise.all(_.uniq(dashboardQuestionIds).map((id) =>- entityCompatibleQuery({ id }, dispatch, cardApi.endpoints.getCard),+ runRtkEndpoint({ id }, dispatch, cardApi.endpoints.getCard),),);} catch (err) {@@ -90,7 +90,7 @@ export const moveDashboardToCollection = createThunkAction(const { id, archived, collection_id: current_collection_id } = dashboard;- await entityCompatibleQuery(+ await runRtkEndpoint({id,collection_id: canonicalCollectionId(collection && collection.id),diff --git a/frontend/src/metabase/dashboard/components/DashboardArchivedEntityBanner.tsx b/frontend/src/metabase/dashboard/components/DashboardArchivedEntityBanner.tsxindex a05ed66f841..86b553826f9 100644--- a/frontend/src/metabase/dashboard/components/DashboardArchivedEntityBanner.tsx+++ b/frontend/src/metabase/dashboard/components/DashboardArchivedEntityBanner.tsx@@ -1,7 +1,7 @@import { Api, dashboardApi } from "metabase/api";import { listTag } from "metabase/api/tags";+import { runRtkEndpoint } from "metabase/api/utils/run-rtk-endpoint";import { ArchivedEntityBanner } from "metabase/archive/components/ArchivedEntityBanner/ArchivedEntityBanner";-import { entityCompatibleQuery } from "metabase/entities/utils";import { useDispatch } from "metabase/redux";import type { Dispatch } from "metabase/redux/store";@@ -42,7 +42,7 @@ export const DashboardArchivedEntityBanner = () => {onMove={({ id }) => moveDashboardToCollection({ id })}onDeletePermanently={() => {const deleteAction = (innerDispatch: Dispatch) =>- entityCompatibleQuery(+ runRtkEndpoint(dashboard.id,innerDispatch,dashboardApi.endpoints.deleteDashboard,diff --git a/frontend/src/metabase/entities/containers/EntityName.tsx b/frontend/src/metabase/entities/containers/EntityName.tsxdeleted file mode 100644index ce5a862b541..00000000000--- a/frontend/src/metabase/entities/containers/EntityName.tsx+++ /dev/null@@ -1,46 +0,0 @@-import { useMemo } from "react";--import { useTranslateContent } from "metabase/i18n/hooks";-import { type ItemWithName, getName } from "metabase/utils/name";--import type { EntityDefinition, EntityId, EntityType } from "./rtk-query";--interface Props {- entityId: EntityId;- entityType: EntityType;-}--/**- * @deprecated use "metabase/api" instead- */-export const EntityName = <Entity extends ItemWithName, EntityWrapper>({- entityType,- entityId,-}: Props) => {- const tc = useTranslateContent();-- const entityDefinition: EntityDefinition<Entity, EntityWrapper> =- useMemo(() => {- // eslint-disable-next-line @typescript-eslint/no-require-imports -- dynamic require due to circular dependencies- const entitiesDefinitions = require("metabase/entities");- return entitiesDefinitions[entityType];- }, [entityType]);-- const {- /**- * Hack: this hook appears to be acquired conditionally, which in- * normal circumstances would violate the rules of React hooks.- * As long as getUseGetQuery is a pure function we have a guarantee that- * the same hook will be used and rules of hooks are not violated.- */- useGetQuery,- } = entityDefinition.rtk.getUseGetQuery("fetch");-- const { data: entity } = useGetQuery({ id: entityId });-- if (!entity) {- return null;- }-- return <span>{tc(getName(entity))}</span>;-};diff --git a/frontend/src/metabase/entities/containers/index.jsx b/frontend/src/metabase/entities/containers/index.jsxdeleted file mode 100644index eaca9b48df2..00000000000--- a/frontend/src/metabase/entities/containers/index.jsx+++ /dev/null@@ -1,43 +0,0 @@-/* eslint-disable react/prop-types */-import { EntityName } from "./EntityName";-import {- EntityListLoader,- entityListLoader,- entityObjectLoader,-} from "./rtk-query";--export function addEntityContainers(entity) {- const ObjectName = entity.nameOne;-- /**- * @deprecated HOCs are deprecated- */- entity.load = ({ id, query, ...props } = {}) =>- entityObjectLoader({- entityType: entity.name,- entityId: id,- entityQuery: query,- ...props,- });-- /**- * @deprecated HOCs are deprecated- */- entity.loadList = ({ query, ...props } = {}) => {- return entityListLoader({- entityType: entity.name,- entityQuery: query,- ...props,- });- };-- entity.ListLoader = ({ query, ...props }) => (- <EntityListLoader entityType={entity.name} entityQuery={query} {...props} />- );- entity.ListLoader.displayName = `${ObjectName}.ListLoader`;-- entity.Name = ({ id, ...props }) => (- <EntityName entityType={entity.name} entityId={id} {...props} />- );- entity.Name.displayName = `${ObjectName}.Name`;-}diff --git a/frontend/src/metabase/entities/containers/rtk-query/EntityListLoader.tsx b/frontend/src/metabase/entities/containers/rtk-query/EntityListLoader.tsxdeleted file mode 100644index 32d22141758..00000000000--- a/frontend/src/metabase/entities/containers/rtk-query/EntityListLoader.tsx+++ /dev/null@@ -1,361 +0,0 @@-import { bindActionCreators } from "@reduxjs/toolkit";-import type { ComponentType, ReactNode } from "react";-import { useEffect, useMemo } from "react";-import { match } from "ts-pattern";-import _ from "underscore";--import {- LoadingAndErrorWrapper as DefaultLoadingAndErrorWrapper,- type LoadingAndErrorWrapperProps,-} from "metabase/common/components/LoadingAndErrorWrapper";-import { useDispatch, useSelector } from "metabase/redux";-import {- setRequestError,- setRequestLoaded,- setRequestLoading,-} from "metabase/redux/requests";-import { capitalize } from "metabase/utils/formatting";-import { isObject } from "metabase-types/guards";--import type {- EntityDefinition,- EntityListQueryResponse,- EntityQuery,- EntityQuerySelector,- EntityType,- EntityTypeSelector,- ListMetadata,- ReloadInterval,- ReloadIntervalSelector,-} from "./types";-import { usePaginatedQuery } from "./usePaginatedQuery";--interface ChildrenProps<Entity, EntityWrapper> {- allError?: unknown;- allFetched?: boolean;- allLoaded?: boolean;- allLoading?: boolean;- entityQuery: EntityQuery;- error: unknown;- fetched: boolean;- loaded: boolean;- loading: boolean;- /**- * list item is EntityWrapper when Props["wrapped"] is true- */- list: EntityWrapper[] | Entity[] | undefined;- metadata: ListMetadata | undefined;- reload: () => void;- total: number | undefined;-}--interface Props<Entity, EntityWrapper> {- allError?: unknown;- allFetched?: boolean;- allLoaded?: boolean;- allLoading?: boolean;- ComposedComponent: (props: ChildrenProps<Entity, EntityWrapper>) => ReactNode;- entityQuery?: EntityQuery | EntityQuerySelector;- entityType: EntityType | EntityTypeSelector;- initialPage?: number;- listName?: string;- loadingAndErrorWrapper?: boolean;- LoadingAndErrorWrapper?: ComponentType<LoadingAndErrorWrapperProps>;- pageSize?: number;- reload?: boolean | ChildrenProps<Entity, EntityWrapper>["reload"]; // reload can be passed as a callback from the outer loader- reloadInterval?: ReloadInterval | ReloadIntervalSelector<Entity>;- selectorName?: "getList" | "getListUnfiltered";- wrapped?: boolean;-}--const transformResponse = <Entity extends object>(- fetched: EntityListQueryResponse<Entity>,-) => {- if (!isObject(fetched) || !fetched.data) {- return { results: fetched, metadata: {} };- }-- const { data, ...metadata } = fetched;- return { results: data, metadata };-};--const isPaginationMetadata = (- value: Record<string, unknown>,-): value is { limit: number; offset: number; total: number } => {- return (- typeof value.limit === "number" &&- typeof value.offset === "number" &&- typeof value.total === "number"- );-};--/**- * Difference between the 2 generic types, using Database entity as an example:- * Entity -> Database from metabase-types/api/database.ts- * EntityWrapper -> Database from metabase-lib/v1/metadata/Database.ts- *- * @deprecated use "metabase/api" instead- */-export function EntityListLoader<Entity, EntityWrapper>({- allError: allErrorProp,- allFetched: allFetchedProp,- allLoaded: allLoadedProp,- allLoading: allLoadingProp,- ComposedComponent,- entityQuery: entityQueryProp,- entityType: entityTypeProp,- initialPage,- listName,- loadingAndErrorWrapper = true,- LoadingAndErrorWrapper = DefaultLoadingAndErrorWrapper,- pageSize,- reload = false,- reloadInterval: reloadIntervalProp,- selectorName = "getList",- wrapped = false,- ...props-}: Props<Entity, EntityWrapper>) {- const dispatch = useDispatch();-- const entityType = useSelector((state) =>- typeof entityTypeProp === "function"- ? entityTypeProp(state, props)- : entityTypeProp,- );-- const entityDefinition: EntityDefinition<Entity, EntityWrapper> =- useMemo(() => {- // eslint-disable-next-line @typescript-eslint/no-require-imports -- dynamic require due to circular dependencies- const entitiesDefinitions = require("metabase/entities");- return entitiesDefinitions[entityType];- }, [entityType]);-- const nonPaginatedEntityQuery = useSelector(- (state) =>- typeof entityQueryProp === "function"- ? entityQueryProp(state, props)- : entityQueryProp,- _.isEqual,- );-- const {- entityQuery,- hasMorePages,- isPaginated,- page,- onNextPage,- onPreviousPage,- setHasMorePages,- } = usePaginatedQuery(nonPaginatedEntityQuery, pageSize, initialPage);- const paginationProps = isPaginated- ? {- hasMorePages,- page,- pageSize,- onNextPage,- onPreviousPage,- }- : undefined;-- const entityOptions = useMemo(() => ({ entityQuery }), [entityQuery]);-- const list = useSelector((state) => {- return match(selectorName)- .with("getList", () => {- return entityDefinition.selectors.getList(state, entityOptions);- })- .with("getListUnfiltered", () => {- return entityDefinition.selectors.getListUnfiltered(- state,- entityOptions,- );- })- .exhaustive();- });-- const fetched = useSelector((state) => {- const value = entityDefinition.selectors.getFetched(state, entityOptions);- return Boolean(value);- });-- const loaded = useSelector((state) => {- const value = entityDefinition.selectors.getLoaded(state, entityOptions);- return Boolean(value);- });-- const loading = useSelector((state) => {- const value = entityDefinition.selectors.getLoading(state, entityOptions);- return Boolean(value);- });-- const error = useSelector((state) => {- return entityDefinition.selectors.getError(state, entityOptions);- });-- const metadata = useSelector((state) => {- return entityDefinition.selectors.getListMetadata(state, entityOptions);- });-- const wrappedList = useMemo(() => {- if (!wrapped || !list) {- return list;- }-- return list.map((object) => entityDefinition.wrapEntity(object, dispatch));- }, [dispatch, list, entityDefinition, wrapped]);-- const reloadInterval = useSelector((state) => {- if (typeof reloadIntervalProp === "function") {- return reloadIntervalProp(state, props, list);- }- return reloadIntervalProp;- });-- const {- data,- error: rtkError,- isFetching,- isLoading,- refetch,- } = entityDefinition.rtk.useListQuery(entityQuery, {- pollingInterval: reloadInterval,- refetchOnMountOrArgChange: reload === true,- });-- const queryKey = useMemo(- () => entityDefinition.getQueryKey(entityQuery),- [entityDefinition, entityQuery],- );-- const listStatePath = useMemo(() => {- return entityDefinition.getListStatePath(entityQuery);- }, [entityDefinition, entityQuery]);-- const requestStatePath = useMemo(() => {- return [...listStatePath, "fetch"];- }, [listStatePath]);-- useEffect(() => {- if (isFetching) {- dispatch(setRequestLoading(requestStatePath, queryKey));- }- }, [dispatch, isFetching, requestStatePath, queryKey]);-- useEffect(() => {- if (rtkError) {- dispatch(setRequestError(requestStatePath, queryKey, rtkError));- }- }, [dispatch, rtkError, requestStatePath, queryKey]);-- useEffect(() => {- if (data && !isFetching) {- const { results, metadata } = transformResponse(data);-- if (isPaginationMetadata(metadata)) {- setHasMorePages(metadata.offset + metadata.limit < metadata.total);- }-- if (!Array.isArray(results)) {- throw new Error(`Invalid response listing ${entityDefinition.name}`);- }-- const normalized = entityDefinition.normalizeList(results);-- const result = {- ...normalized,- metadata,- entityQuery,- };-- dispatch({- type: entityDefinition.actionTypes.FETCH_LIST,- payload: result,- });-- // NOTE Atte KeinΓ€nen 8/23/17:- // Dispatch `setRequestLoaded` after clearing the call stack because we want to the actual data to be updated- // before we notify components via `state.requests.fetches` that fetching the data is completed- setTimeout(() => dispatch(setRequestLoaded(requestStatePath, queryKey)));- }- }, [- dispatch,- data,- entityDefinition,- entityQuery,- isFetching,- requestStatePath,- queryKey,- setHasMorePages,- ]);-- // merge props passed in from stacked Entity*Loaders:- const allError = error || (allErrorProp ?? null);- const allFetched = fetched && (allFetchedProp ?? true);- const allLoaded = loaded && (allLoadedProp ?? true);- const allLoading = loading || (allLoadingProp ?? false);- const finalListName = listName || entityDefinition.nameMany;- const total = Array.isArray(data) ? undefined : data?.total;-- const actionCreators = useMemo(() => {- return bindActionCreators(entityDefinition.actions, dispatch);- }, [entityDefinition.actions, dispatch]);-- const children = (- <ComposedComponent- {...actionCreators}- {...paginationProps}- {...props}- {...{- [finalListName]: wrappedList,- [`reload${capitalize(finalListName)}`]: refetch,- }}- allError={allError}- allFetched={allFetched}- allLoaded={allLoaded}- allLoading={allLoading}- entityQuery={entityQuery}- error={error}- fetched={fetched}- list={wrappedList}- loaded={loaded}- loading={loading || isFetching}- metadata={metadata}- reload={refetch}- total={total}- />- );-- if (loadingAndErrorWrapper) {- return (- <LoadingAndErrorWrapper- loading={!allFetched || isLoading}- error={allError}- noWrapper- >- {children}- </LoadingAndErrorWrapper>- );- }-- return children;-}--/**- * @deprecated HOCs are deprecated- */-export const entityListLoader =- <Entity, EntityWrapper>(eolProps: any) =>- (- ComposedComponent: (- props: ChildrenProps<Entity, EntityWrapper>,- ) => ReactNode,- ) =>- function EntityListLoaderWrapper(props: any) {- return (- <EntityListLoader- ComposedComponent={ComposedComponent}- {...props}- {...eolProps}- />- );- };diff --git a/frontend/src/metabase/entities/containers/rtk-query/EntityObjectLoader.tsx b/frontend/src/metabase/entities/containers/rtk-query/EntityObjectLoader.tsxdeleted file mode 100644index 86a3e580182..00000000000--- a/frontend/src/metabase/entities/containers/rtk-query/EntityObjectLoader.tsx+++ /dev/null@@ -1,283 +0,0 @@-import { bindActionCreators } from "@reduxjs/toolkit";-import { skipToken } from "@reduxjs/toolkit/query/react";-import type { ComponentType, ReactNode } from "react";-import { useEffect, useMemo } from "react";-import { match } from "ts-pattern";--import {- LoadingAndErrorWrapper as DefaultLoadingAndErrorWrapper,- type LoadingAndErrorWrapperProps,-} from "metabase/common/components/LoadingAndErrorWrapper";-import { useDispatch, useSelector } from "metabase/redux";-import {- setRequestError,- setRequestLoaded,- setRequestLoading,-} from "metabase/redux/requests";-import type { Dispatch } from "metabase/redux/store";--import type {- EntityDefinition,- EntityId,- EntityIdSelector,- EntityQuery,- EntityQuerySelector,- EntityType,- EntityTypeSelector,- FetchType,- RequestType,-} from "./types";--interface ChildrenProps<Entity, EntityWrapper> {- dispatch: Dispatch;- error: unknown;- fetched: boolean;- loading: boolean;- /**- * object is EntityWrapper when Props["wrapped"] is true- */- object: EntityWrapper | Entity | undefined;- reload: () => void;-}--interface Props<Entity, EntityWrapper> {- ComposedComponent: (props: ChildrenProps<Entity, EntityWrapper>) => ReactNode;- entityAlias?: string;- entityId: EntityId | EntityIdSelector | undefined;- entityQuery?: EntityQuery | EntityQuerySelector;- entityType: EntityType | EntityTypeSelector;- fetchType?: FetchType;- loadingAndErrorWrapper?: boolean;- LoadingAndErrorWrapper?: ComponentType<LoadingAndErrorWrapperProps>;- reload?: boolean | ChildrenProps<Entity, EntityWrapper>["reload"]; // reload can be passed as a callback from the outer loader- requestType?: RequestType;- selectorName?: "getObject" | "getObjectUnfiltered";- wrapped?: boolean;-}--const defaultTransformResponse = (data: unknown, _query: EntityQuery) => data;--/**- * Difference between the 2 generic types, using Database entity as an example:- * Entity -> Database from metabase-types/api/database.ts- * EntityWrapper -> Database from metabase-lib/v1/metadata/Database.ts- *- * @deprecated use "metabase/api" instead- */-export function EntityObjectLoader<Entity, EntityWrapper>({- ComposedComponent,- entityAlias,- entityId: entityIdProp,- entityQuery: entityQueryProp,- entityType: entityTypeProp,- fetchType = "fetch",- loadingAndErrorWrapper = true,- LoadingAndErrorWrapper = DefaultLoadingAndErrorWrapper,- reload = false,- requestType = "fetch",- selectorName = "getObject",- wrapped = false,- ...props-}: Props<Entity, EntityWrapper>) {- const dispatch = useDispatch();-- const entityType = useSelector((state) =>- typeof entityTypeProp === "function"- ? entityTypeProp(state, props)- : entityTypeProp,- );-- const entityDefinition: EntityDefinition<Entity, EntityWrapper> =- useMemo(() => {- // eslint-disable-next-line @typescript-eslint/no-require-imports -- dynamic require due to circular dependencies- const entitiesDefinitions = require("metabase/entities");- return entitiesDefinitions[entityType];- }, [entityType]);-- const entityId = useSelector((state) =>- typeof entityIdProp === "function"- ? entityIdProp(state, props)- : entityIdProp,- );-- const entityQuery = useSelector((state) =>- typeof entityQueryProp === "function"- ? entityQueryProp(state, props)- : entityQueryProp,- );-- const finalQuery = useMemo(- () => ({ id: entityId, ...entityQuery }),- [entityId, entityQuery],- );-- const {- action = entityDefinition.actionTypes.FETCH,- transformResponse = defaultTransformResponse,- /**- * Hack: this hook appears to be acquired conditionally, which in- * normal circumstances would violate the rules of React hooks.- * As long as fetchType never changes during component's lifecycle- * and getUseGetQuery is a pure function, we have a guarantee that- * the same hook will be used and rules of hooks are not violated.- */- useGetQuery,- } = entityDefinition.rtk.getUseGetQuery(fetchType);-- const {- data,- error: rtkError,- isFetching,- refetch,- } = useGetQuery(entityId != null ? finalQuery : skipToken, {- refetchOnMountOrArgChange: reload === true,- });-- const queryKey = useMemo(- () => entityDefinition.getQueryKey(finalQuery),- [entityDefinition, finalQuery],- );-- const objectStatePath = useMemo(() => {- if (!entityId) {- return [];- }-- return entityDefinition.getObjectStatePath(entityId);- }, [entityDefinition, entityId]);-- const requestStatePath = useMemo(() => {- return [...objectStatePath, requestType];- }, [objectStatePath, requestType]);-- useEffect(() => {- if (isFetching) {- dispatch(setRequestLoading(requestStatePath, queryKey));- }- }, [dispatch, isFetching, requestStatePath, queryKey]);-- useEffect(() => {- if (rtkError) {- dispatch(setRequestError(requestStatePath, queryKey, rtkError));- }- }, [dispatch, rtkError, requestStatePath, queryKey]);-- useEffect(() => {- if (data && !isFetching) {- const transformed = transformResponse(data, finalQuery);- const normalized = entityDefinition.normalize(transformed);-- dispatch({ type: action, payload: normalized });-- // NOTE Atte KeinΓ€nen 8/23/17:- // Dispatch `setRequestLoaded` after clearing the call stack because we want to the actual data to be updated- // before we notify components via `state.requests.fetches` that fetching the data is completed- setTimeout(() => dispatch(setRequestLoaded(requestStatePath, queryKey)));- }- }, [- action,- dispatch,- data,- entityDefinition,- finalQuery,- isFetching,- transformResponse,- requestStatePath,- queryKey,- ]);-- const entityOptions = useMemo(- () => ({ entityId, requestType }),- [entityId, requestType],- );-- const object = useSelector((state) => {- return match(selectorName)- .with("getObject", () => {- return entityDefinition.selectors.getObject(state, entityOptions);- })- .with("getObjectUnfiltered", () => {- return entityDefinition.selectors.getObjectUnfiltered(- state,- entityOptions,- );- })- .exhaustive();- });-- const fetched = useSelector((state) => {- const value = entityDefinition.selectors.getFetched(state, entityOptions);- return Boolean(value);- });-- const loading = useSelector((state) => {- const value = entityDefinition.selectors.getLoading(state, entityOptions);- return Boolean(value);- });-- const error = useSelector((state) => {- return entityDefinition.selectors.getError(state, entityOptions);- });-- const actionCreators = useMemo(() => {- return bindActionCreators(entityDefinition.actions, dispatch);- }, [entityDefinition.actions, dispatch]);-- const wrappedObject = useMemo(() => {- if (!wrapped || !object) {- return object;- }-- return entityDefinition.wrapEntity(object, dispatch);- }, [dispatch, object, entityDefinition, wrapped]);-- const children = (- <ComposedComponent- {...actionCreators}- {...props}- {...{- [entityAlias || entityDefinition.nameOne]: wrappedObject,- }}- dispatch={dispatch}- error={error}- fetched={fetched}- loading={loading || isFetching}- object={wrappedObject}- reload={refetch}- />- );-- if (loadingAndErrorWrapper) {- return (- <LoadingAndErrorWrapper- loading={!fetched && entityId != null}- error={error}- noWrapper- >- {children}- </LoadingAndErrorWrapper>- );- }-- return children;-}--/**- * @deprecated HOCs are deprecated- */-export const entityObjectLoader =- <Entity, EntityWrapper>(eolProps: any) =>- (- ComposedComponent: (- props: ChildrenProps<Entity, EntityWrapper>,- ) => ReactNode,- ) =>- function EntityObjectLoaderWrapper(props: any) {- return (- <EntityObjectLoader- ComposedComponent={ComposedComponent}- {...props}- {...eolProps}- />- );- };diff --git a/frontend/src/metabase/entities/containers/rtk-query/index.ts b/frontend/src/metabase/entities/containers/rtk-query/index.tsdeleted file mode 100644index 9cffd01593a..00000000000--- a/frontend/src/metabase/entities/containers/rtk-query/index.ts+++ /dev/null@@ -1,3 +0,0 @@-export * from "./EntityListLoader";-export * from "./EntityObjectLoader";-export * from "./types";diff --git a/frontend/src/metabase/entities/containers/rtk-query/types/entities.ts b/frontend/src/metabase/entities/containers/rtk-query/types/entities.tsdeleted file mode 100644index fb9ce835d51..00000000000--- a/frontend/src/metabase/entities/containers/rtk-query/types/entities.ts+++ /dev/null@@ -1,119 +0,0 @@-import type { BaseQueryFn, QueryDefinition } from "@reduxjs/toolkit/query";--import type { TagType } from "metabase/api/tags";-import type { Dispatch, State } from "metabase/redux/store";--import type { UseQuery } from "./rtk";--export type Selector<T> = (state: State, entityOptions: EntityOptions) => T;--export type RequestType = "fetch" | string;--export type FetchType = string;--export type EntityId = string | number;--export type EntityIdSelector = (- state: State,- props: unknown,-) => EntityId | undefined;--export type EntityQuery = unknown;--export type EntityQuerySelector = (state: State, props: unknown) => EntityQuery;--export type ReloadInterval = number;--export type ReloadIntervalSelector<Entity> = (- state: State,- props: unknown,- list: Entity[] | undefined,-) => ReloadInterval | undefined;--/**- * Corresponds to the "name" parameter passed to "createEntity" function.- * There should be an entry here for every "createEntity" function call.- */-export type EntityType =- | "alerts"- | "bookmarks"- | "documents"- | "pulses"- | "questions"- | "revisions"- | "search"- | "segments"- | "snippetCollections"- | "snippets"- | "tables"- | "timelines"- | "users";--export type EntityTypeSelector = (state: State, props: unknown) => EntityType;--export type EntityObjectOptions = {- entityId: EntityId | undefined;- requestType: RequestType;-};--export type EntityListOptions = {- entityQuery: EntityQuery;-};--export type EntityOptions = EntityObjectOptions | EntityListOptions;--export type EntityListQueryResponse<Data> =- | Data- | {- data: Data;- total: number;- };--export interface EntityDefinition<Entity, EntityWrapper> {- actions: {- [actionName: string]: (...args: unknown[]) => unknown;- };- actionTypes: Record<string, string>;- getListStatePath: (entityQuery: EntityQuery) => string;- getObjectStatePath: (entityId: EntityId) => string;- getQueryKey: (entityQuery: EntityQuery) => string;- name: string;- nameMany: string;- nameOne: string;- normalize: (object: unknown) => { object: unknown };- normalizeList: (list: unknown) => { list: unknown };- rtk: {- getUseGetQuery: (fetchType: FetchType) => {- action?: string;- transformResponse?: (data: Entity, query: EntityQuery) => unknown;- useGetQuery: UseQuery<- QueryDefinition<unknown, BaseQueryFn, TagType, Entity>- >;- };- useListQuery: UseQuery<- QueryDefinition<- unknown,- BaseQueryFn,- TagType,- EntityListQueryResponse<Entity[]>- >- >;- };-- selectors: {- getError: Selector<unknown | null | undefined>;- getFetched: Selector<boolean | undefined>;- getList: Selector<Entity[] | undefined>;- getListMetadata: Selector<ListMetadata | undefined>;- getListUnfiltered: Selector<Entity[] | undefined>;- getLoaded: Selector<boolean | undefined>;- getLoading: Selector<boolean | undefined>;- getObject: Selector<Entity | undefined>;- getObjectUnfiltered: Selector<Entity | undefined>;- };- wrapEntity: (object: Entity, dispatch: Dispatch) => EntityWrapper;-}--export interface ListMetadata {- total?: number;-}diff --git a/frontend/src/metabase/entities/containers/rtk-query/types/index.ts b/frontend/src/metabase/entities/containers/rtk-query/types/index.tsdeleted file mode 100644index 85246958c74..00000000000--- a/frontend/src/metabase/entities/containers/rtk-query/types/index.ts+++ /dev/null@@ -1 +0,0 @@-export * from "./entities";diff --git a/frontend/src/metabase/entities/containers/rtk-query/usePaginatedQuery.ts b/frontend/src/metabase/entities/containers/rtk-query/usePaginatedQuery.tsdeleted file mode 100644index d2f80bdcd60..00000000000--- a/frontend/src/metabase/entities/containers/rtk-query/usePaginatedQuery.ts+++ /dev/null@@ -1,49 +0,0 @@-import { useCallback, useMemo, useState } from "react";--import type { EntityQuery } from "./types";--/**- * @deprecated exists for backwards compatibility- */-export const usePaginatedQuery = (- entityQuery: EntityQuery,- pageSize: number | undefined,- initialPage: number | undefined,-) => {- const isPaginated = typeof pageSize === "number";- const [page, setPage] = useState(initialPage || 0);- const [hasMorePages, setHasMorePages] = useState<boolean | null>(null);- const limit = pageSize;- const offset = isPaginated ? pageSize * page : undefined;-- const handleNextPage = useCallback(() => {- setPage((page) => page + 1);- setHasMorePages(null);- }, []);-- const handlePreviousPage = useCallback(() => {- setPage((page) => page - 1);- setHasMorePages(true);- }, []);-- const paginatedQuery = useMemo(() => {- return { ...(entityQuery ?? {}), limit, offset };- }, [entityQuery, limit, offset]);-- if (!isPaginated) {- return {- entityQuery,- setHasMorePages,- };- }-- return {- entityQuery: paginatedQuery,- hasMorePages,- isPaginated,- page,- onNextPage: hasMorePages ? handleNextPage : null,- onPreviousPage: page > 0 ? handlePreviousPage : null,- setHasMorePages,- };-};diff --git a/frontend/src/metabase/entities/index.ts b/frontend/src/metabase/entities/index.tsdeleted file mode 100644index c72c40d91be..00000000000--- a/frontend/src/metabase/entities/index.ts+++ /dev/null@@ -1,74 +0,0 @@-/*- * # Entities abstract the interface between the back-end and the front-end.- *- * ## Endpoint requirements for entities:- *- * When fetching a list, each item of the list must include an `id` key/value pair.- *- * JSON must wrap response inside a `{ "data" : { β¦your data } }` structure.- *- * ## Required Properties:- *- * name:- * a string in plural form- * examples:- * "questions", "dashboards"- *- * path:- * a uri- * starting with "/api/"- * conventionally followed by the entity name in singular form- * examples:- * "/api/card", "/api/dashboard"- *- * ## Optional properties:- *- * api:- *- * here you can override the basic entity methods like `list`, `create`, `get`, `update`, `delete` (OR see `path` below)- *- * schema:- * normalizr schema- * default:- * `new schema.Entity(entity.name)`- *- * ## How to create a bare-bones entity- *- * Say we want to create a "books" entity, to be able to fetch a list of "books".- *- * Add the following line to `frontend/src/metabase/entities.index.js`:- *- * export { default as books } from "./books"- *- * Create file `frontend/src/metabase/entities/books.js`- *- * Add the following to it:- *- * import { createEntity } from "./utils";-- * const Books = createEntity({- * name: "books",- * nameOne: "book",- * path: "/api/book",- * });- *- * export default Books;- *- * ## How to consume an entity:- *- * Near the top of a container file, import the entity:- *- * import Book from "metabase/entities/books";- *- * Near the bottom of the container file, add the entity to a `compose` statement:- *- * export default _.compose(- * Book.loadList(),- * connect(mapStateToProps),- * )(BookContainer);- */--// All entities have been migrated to "metabase/api"; this barrel intentionally-// exports nothing. Keep the empty export so the file stays a module, not a-// script.-export {};diff --git a/frontend/src/metabase/entities/utils.ts b/frontend/src/metabase/entities/utils.tsdeleted file mode 100644index 0a4ab3a198a..00000000000--- a/frontend/src/metabase/entities/utils.ts+++ /dev/null@@ -1,1345 +0,0 @@-import type { Reducer } from "@reduxjs/toolkit";-import { createSelector } from "@reduxjs/toolkit";-import { getIn, merge } from "icepick";-import inflection from "inflection"; // NOTE: need to use inflection directly here due to circular dependency-import { type Schema, denormalize, normalize, schema } from "normalizr";-import createCachedSelector from "re-reselect";-import type React from "react";-import _ from "underscore";--import { DELETE, GET, POST, PUT } from "metabase/api/legacy-client";-import { PLUGIN_ENTITIES } from "metabase/plugins";-import { combineReducers, compose, withAction } from "metabase/redux";-import {- type RequestsStateTree,- requestsReducer,- setRequestError,- setRequestLoaded,- setRequestLoading,- setRequestPromise,- setRequestUnloaded,-} from "metabase/redux/requests";-import type { Dispatch, EntitiesState, State } from "metabase/redux/store";-import { addUndo } from "metabase/redux/undo";-import { delay } from "metabase/utils/promise";--// backend returns model = "card" instead of "question"-export const entityTypeForModel = (model: string): string => {- if (model === "card" || model === "dataset" || model === "metric") {- return "questions";- }- return `${model}s`;-};--export const entityTypeForObject = (- object?: { model: string } | null,-): string | undefined =>- object ? entityTypeForModel(object.model) : undefined;--export const entityForObject = (object?: { model: string } | null) => {- // eslint-disable-next-line @typescript-eslint/no-require-imports -- dynamic require due to circular dependencies- const entities = require("metabase/entities");- const enterpriseEntities = PLUGIN_ENTITIES.entities;- const entityType = entityTypeForObject(object);- if (!entityType) {- return undefined;- }- return { ...entities, ...enterpriseEntities }[entityType];-};--const EMPTY_ENTITY_QUERY = {};--export type EntityId = string | number;--/**- * The minimum shape required of an entity object: anything with an `id`.- * Concrete entity types (Collection, Card, Dashboard, β¦) extend this implicitly- * by having an `id` field. We avoid an `[key: string]: unknown` index signature- * because it would prevent narrower types from being assignable to `EntityObject`.- */-export type EntityObject = {- id: EntityId;- name?: string;- collection?: unknown;-};--type NormalizedPayload = {- entities?: Record<string, Record<EntityId, EntityObject>>;- result?: EntityId | EntityId[];-};--type EntityAction = {- payload?: NormalizedPayload;-};--// The entity framework is a runtime abstraction β consumers define selectors,-// action creators, and object methods with per-entity concrete types that can't be-// statically expressed here. These aliases document the intent of each `any`:--/** Redux dispatch accepted by entity actions. */--type AnyDispatch = (action: any) => any;-/** Redux getState accepted by entity thunks. */--type AnyGetState = () => any;-/** Action creator produced by `entity.actions` / `entity.objectActions`. Each entity- * defines its own specific signatures, so we use a broad callable type here. */--type EntityActionCreator = (...args: any[]) => any;-/** Entity selector signature. Each entity defines its own specific selector signatures. */--type EntitySelector = (state: any, ...args: any[]) => any;-/** Entity query passed to list/fetch endpoints. Concrete shape depends on the entity. */--type EntityQuery = any;--/** Named selectors that every entity must expose. */-export type EntitySelectors = {- getObject: EntitySelector;- getList: EntitySelector;- getEntityIds: EntitySelector;- getLoading: EntitySelector;- getLoaded: EntitySelector;- getFetched: EntitySelector;- getError: EntitySelector;- getListMetadata: EntitySelector;-};--/** Shape returned by createEntity */-export type Entity = {- // Names- name: string;- nameOne: string;- nameMany: string;- displayNameOne: string;- displayNameMany: string;-- // Schema- schema: schema.Entity;- path?: string;-- // API β each method may accept any arguments (raw data + options objects)-- api: {- list?: (...args: any[]) => Promise<- | EntityObject[]- | {- data: EntityObject[];- [key: string]: unknown;- }- >;- create: (...args: any[]) => Promise<any>;- get: (...args: any[]) => Promise<any>;- update: (...args: any[]) => Promise<any>;- delete: (...args: any[]) => Promise<any>;- };-- // Action type constants. The values are strings at runtime, but consumers use them- // with `builder.addCase(actionType, reducer)` and rely on the second arg being typed- // as a `PayloadAction<any>` (matching the JS framework's behaviour). Typing them as- // `any` here preserves that ergonomic.- actionTypes: {- CREATE: any;-- FETCH: any;-- UPDATE: any;-- DELETE: any;-- FETCH_LIST: any;-- INVALIDATE_LISTS_ACTION: any;-- [key: string]: any;- };-- actionDecorators: Record<- string,- (action: EntityActionCreator) => EntityActionCreator- >;-- // Path helpers- getQueryKey: (entityQuery: EntityQuery) => string;- getObjectStatePath: (entityId: EntityId) => (string | EntityId)[];- getListStatePath: (entityQuery: EntityQuery) => string[];-- // Normalize helpers- normalize: (- object: EntityObject,- entitySchema?: schema.Entity,- ) => NormalizedPayload & { object: EntityObject };- normalizeList: (- list: EntityObject[],- entitySchema?: schema.Entity,- ) => NormalizedPayload & { list: EntityObject[] };-- // Actions (thunk action creators) β each entity defines its own signatures- objectActions: Record<string, EntityActionCreator> & {- fetch: EntityActionCreator;- create: EntityActionCreator;- update: EntityActionCreator;- delete: EntityActionCreator;- };-- actions: Record<string, EntityActionCreator> & {- fetchList: EntityActionCreator;- invalidateLists: EntityActionCreator;- fetch: EntityActionCreator;- create: EntityActionCreator;- update: EntityActionCreator;- delete: EntityActionCreator;- };-- // Extract entity from dispatched action result. The return type depends on the- // action's normalized payload and is best handled dynamically by consumers.-- HACK_getObjectFromAction: (action: any) => any;-- // Selectors- selectors: EntitySelectors;-- // Reducers- reducer?: EntitiesReducer;- reducers: {- slice: EntitiesReducer;- list: EntityListReducer;- };- requestsReducer: (- state: RequestsStateTree,- action: { type: string },- ) => RequestsStateTree;- actionShouldInvalidateLists: (action: { type: string }) => boolean;-- // Writable properties (subset of entity fields sent to the API)- writableProperties?: string[];-- // Wrap entity object with bound selectors/actions. The wrapper preserves the- // input's properties and adds the entity's bound objectActions- // (e.g. `getName()`, `getIcon()`). Each entity defines its own object methods,- // so we return `any` to allow consumers to use any wrapper-provided method.- wrapEntity: (object: any, dispatch?: AnyDispatch | null) => any;-- // HOC factories and JSX components added by addEntityContainers at construction time.- // These are always present on the returned entity, so consumers can rely on them.- /** @deprecated HOCs are deprecated */-- load: (opts?: Record<string, unknown>) => any;- /** @deprecated HOCs are deprecated */-- loadList: (opts?: Record<string, unknown>) => any;-- ListLoader: React.ComponentType<any>;- // Accept nullable/undefined IDs: consumers commonly pass optional dashboard/card ids- Name: React.ComponentType<- { id: EntityId | null | undefined } & Record<string, any>- >;-- rtk: EntityRtkBridge;-};--/**- * Optional RTK Query bridge that a few entities use to expose RTK Query hooks- * through the entity abstraction. Structure is deliberately loose β each entity- * attaches a different set of helpers.- */--type EntityRtkBridge = Record<string, any>;--/**- * A single value held in an entity-list cache slice (`state.entities.<name>_list`):- * either a flat array of ids ("default" list, no `entityQuery`) or a per-query- * payload of result + result metadata. The `list` field comes straight from- * the dispatched action payload, so it's typed `unknown` here.- */-type EntityListEntry = EntityId[] | { list: unknown; metadata?: unknown };--/**- * Per-value type for any slice managed by the entities reducer. Concrete slices- * only hold one of these kinds β entity slices hold `EntityObject`s, list- * slices hold `EntityListEntry`s β but `combineReducers` requires reducers in- * the same map to share a state type (reducer state is invariant), so both- * reducers below operate on this union.- */-type EntitySliceValue = EntityObject | EntityListEntry;--/** Reducer for a single entity slice (`state.entities.<name>`). */-type EntitiesReducer = Reducer<Record<string, EntitySliceValue>>;--/** Reducer for an entity-list cache slice (`state.entities.<name>_list`). */-type EntityListReducer = Reducer<Record<string, EntitySliceValue>>;--type EntityDef = {- name: string;- nameOne?: string;- nameMany?: string;- displayNameOne?: string;- displayNameMany?: string;- path?: string;- schema?: schema.Entity;- api?: Partial<Entity["api"]>;- writableProperties?: string[];- actionTypes?: Record<string, string>;- actionDecorators?: Record<- string,- (action: EntityActionCreator) => EntityActionCreator- >;- objectActions?: Record<string, EntityActionCreator>;- actions?: Record<string, EntityActionCreator>;- selectors?: Partial<EntitySelectors>;- createSelectors?: (- defaultSelectors: Partial<EntitySelectors>,- ) => Partial<EntitySelectors>;- // Reducers in entity defs typically destructure `{ type, payload }` from the action- // and accept any payload shape, so we type the action loosely here.-- reducer?: EntitiesReducer;- wrapEntity?: Entity["wrapEntity"];- requestsReducer?: Entity["requestsReducer"];- actionShouldInvalidateLists?: Entity["actionShouldInvalidateLists"];- rtk?: EntityRtkBridge | (() => EntityRtkBridge);- // Per-entity custom fields (e.g. `getAnalyticsMetadata`, `form`, `forms`).- // These are attached to the entity object and used by entity-aware machinery.-- [key: string]: any;-};--// helper for working with normalizr-// merge each entity from newEntities with existing entity, if any-// this ensures partial entities don't overwrite existing entities with more properties-export function mergeEntities<T = EntitiesState>(- entities: T,- newEntities: Partial<T>,-): T {- const result = { ...entities };- // Casting is necessary here because Object.keys always returns string[]- const ids = Object.keys(newEntities) as Array<keyof T>;-- for (const id of ids) {- const entry = newEntities[id];- if (entry == null) {- delete result[id];- } else {- result[id] = { ...(result[id] ?? {}), ...entry };- }- }- return result;-}--// helper for working with normalizr-// reducer that merges payload.entities-export function handleEntities(- actionPattern: RegExp,- entityType: string,- reducer?: EntitiesReducer,-): EntitiesReducer {- return (state, action) => {- const entities = getIn(action, ["payload", "entities", entityType]);- if (state && actionPattern.test(action.type) && entities) {- state = mergeEntities(state, entities);- }- return reducer?.(state, action) ?? state ?? {};- };-}--/**- * @deprecated use "metabase/api" instead- */-export function createEntity(def: EntityDef): Entity {- // We use a mutable object internally during construction- // then return it typed as Entity at the end.- const entity = { ...def } as Entity;-- if (!entity.nameOne) {- entity.nameOne = inflection.singularize(entity.name);- }- if (!entity.nameMany) {- entity.nameMany = entity.name;- }-- if (!entity.displayNameOne) {- entity.displayNameOne = entity.nameOne;- }- if (!entity.displayNameMany) {- entity.displayNameMany = entity.nameMany;- }-- // defaults- if (!entity.schema) {- entity.schema = new schema.Entity(entity.name);- }-- if (entity.path) {- const path = entity.path;- const defaultApi: Entity["api"] = {- list: GET(`${path}`),- create: POST(`${path}`),- get: GET(`${path}/:id`),- update: PUT(`${path}/:id`),- delete: DELETE(`${path}/:id`),- };- // merge: user-provided overrides win over path-derived defaults- entity.api = { ...defaultApi, ...entity.api };- }-- const getQueryKey = (entityQuery: EntityQuery): string =>- JSON.stringify(entityQuery || null);- const getObjectStatePath = (entityId: EntityId): (string | EntityId)[] => [- "entities",- entity.name,- entityId,- ];- const getListStatePath = (entityQuery: EntityQuery): string[] =>- ["entities", entity.name + "_list"].concat(getQueryKey(entityQuery));-- entity.getQueryKey = getQueryKey;- entity.getObjectStatePath = getObjectStatePath;- entity.getListStatePath = getListStatePath;-- const getWritableProperties = (object: EntityObject): Partial<EntityObject> =>- entity.writableProperties != null- ? _.pick(object, "id", ...entity.writableProperties)- : object;-- // ACTION TYPES- const CREATE_ACTION = `metabase/entities/${entity.name}/CREATE`;- const FETCH_ACTION = `metabase/entities/${entity.name}/FETCH`;- const UPDATE_ACTION = `metabase/entities/${entity.name}/UPDATE`;- const DELETE_ACTION = `metabase/entities/${entity.name}/DELETE`;- const FETCH_LIST_ACTION = `metabase/entities/${entity.name}/FETCH_LIST`;- const INVALIDATE_LISTS_ACTION = `metabase/entities/${entity.name}/INVALIDATE_LISTS`;-- entity.actionTypes = {- CREATE: CREATE_ACTION,- FETCH: FETCH_ACTION,- UPDATE: UPDATE_ACTION,- DELETE: DELETE_ACTION,- FETCH_LIST: FETCH_LIST_ACTION,- INVALIDATE_LISTS_ACTION: INVALIDATE_LISTS_ACTION,- ...(def.actionTypes || {}),- };-- entity.actionDecorators = {- ...(def.actionDecorators || {}),- };-- // normalize helpers- entity.normalize = (- object: EntityObject,- entitySchema: schema.Entity = entity.schema,- ) => ({- object,- [entity.nameOne]: object,- ...normalize(object, entitySchema),- });-- entity.normalizeList = (- list: EntityObject[],- entitySchema: schema.Entity = entity.schema,- ) => ({- list,- [entity.nameMany]: list,- ...normalize(list, [entitySchema]),- });-- // thunk decorators:-- // same as withRequestState, but with automatic prefix-- function withEntityRequestState(- getSubStatePath: (...args: any[]) => (string | EntityId)[],- ) {- return withRequestState((...args: any[]) => [- "entities",- entity.name,- ...getSubStatePath(...args).map(String),- ]);- }-- function withEntityActionDecorators(- action: string,- ): (fn: EntityActionCreator) => EntityActionCreator {- return entity.actionDecorators[action] || ((fn: EntityActionCreator) => fn);- }-- // `objectActions` are for actions that accept an entity as their first argument,- // and they are bound to instances when `wrapped: true` is passed to `EntityListLoader`- // compose(decorator, decorator)(fn) loses types through multiple levels; makeAction recovers them- entity.objectActions = {- fetch: compose<EntityActionCreator>(- withAction(FETCH_ACTION),- withCachedDataAndRequestState(- ({ id }: { id: EntityId }) => [...getObjectStatePath(id).map(String)],- ({ id }: { id: EntityId }) => [- ...getObjectStatePath(id).map(String),- "fetch",- ],- (entityQuery: EntityQuery) => getQueryKey(entityQuery),- ),- withEntityActionDecorators("fetch"),- )(- (entityQuery: EntityQuery, options: Record<string, unknown> = {}) =>- async (dispatch: AnyDispatch, getState: AnyGetState) =>- entity.normalize(- await entity.api.get?.(entityQuery, options, dispatch, getState),- ),- ),-- create: compose<EntityActionCreator>(- withAction(CREATE_ACTION),- withEntityRequestState(() => ["create"]),- withEntityActionDecorators("create"),- )(- (entityObject: EntityObject) =>- async (dispatch: AnyDispatch, getState: AnyGetState) => {- return entity.normalize(- await entity.api.create?.(- getWritableProperties(entityObject),- dispatch,- getState,- ),- );- },- ),-- update: compose<EntityActionCreator>(- withAction(UPDATE_ACTION),- withEntityRequestState((object: EntityObject) => [- String(object.id),- "update",- ]),- withEntityActionDecorators("update"),- )(- (- entityObject: EntityObject,- updatedObject: Partial<EntityObject> | null = null,- {- notify,- }: {- notify?: { undo?: boolean; subject?: string; verb?: string } | false;- } = {},- ) =>- async (dispatch: AnyDispatch, getState: AnyGetState) => {- // save the original object for undo- const originalObject = getObject(getState(), {- entityId: entityObject.id,- });- // If a second object is provided just take the id from the first and- // update it with all the properties in the second- if (updatedObject) {- entityObject = { id: entityObject.id, ...updatedObject };- }-- const result = entity.normalize(- await entity.api.update?.(- getWritableProperties(entityObject),- dispatch,- getState,- ),- );-- if (notify) {- if (notify.undo) {- // pick only the attributes that were updated- const undoObject = _.pick(- originalObject,- ...Object.keys(updatedObject || {}),- );- dispatch(- addUndo({- actions: [- entity.objectActions.update(- entityObject,- undoObject,- // don't show an undo for the undo- { notify: false },- ),- ],- ...notify,- }),- );- } else {- dispatch(addUndo(notify));- }- }- return result;- },- ),-- delete: compose<EntityActionCreator>(- withAction(DELETE_ACTION),- withEntityRequestState((object: EntityObject) => [- String(object.id),- "delete",- ]),- withEntityActionDecorators("delete"),- )(- (entityObject: EntityObject) =>- async (dispatch: AnyDispatch, getState: AnyGetState) => {- await entity.api.delete?.(entityObject, dispatch, getState);- return {- entities: { [entity.name]: { [entityObject.id]: null } },- result: entityObject.id,- };- },- ),-- // user defined object actions should override defaults- ...(def.objectActions || {}),- };-- // ACTION CREATORS- entity.actions = {- fetchList: compose<EntityActionCreator>(- withAction(FETCH_LIST_ACTION),- withCachedDataAndRequestState(- (entityQuery: EntityQuery) => [...getListStatePath(entityQuery)],- (entityQuery: EntityQuery) => [- ...getListStatePath(entityQuery),- "fetch",- ],- (entityQuery: EntityQuery) => entity.getQueryKey(entityQuery),- ),- )(- (entityQuery: EntityQuery = null) =>- async (dispatch: AnyDispatch, getState: AnyGetState) => {- const fetched = await entity.api.list?.(- entityQuery || EMPTY_ENTITY_QUERY,- dispatch,- getState,- );-- let results: EntityObject[] | undefined;- let metadata: Record<string, unknown> = {};-- if (!fetched || _.isArray(fetched)) {- results = fetched;- } else {- const { data, ...rest } = fetched;- results = data;- metadata = rest;- }-- if (!Array.isArray(results)) {- throw `Invalid response listing ${entity.name}`;- }- return {- ...entity.normalizeList(results),- metadata,- entityQuery,- };- },- ),-- invalidateLists: compose<EntityActionCreator>(- withAction(INVALIDATE_LISTS_ACTION),- withEntityActionDecorators("invalidateLists"),- )(() => null),-- // user defined actions should override defaults- ...entity.objectActions,- ...(def.actions || {}),- };-- entity.HACK_getObjectFromAction = (- rawAction: EntityAction | undefined,- ): EntityObject | EntityObject[] | NormalizedPayload | undefined => {- const { payload } = rawAction ?? {};- if (payload && "entities" in payload && "result" in payload) {- if (Array.isArray(payload.result)) {- return payload.result.map((id) => payload.entities![entity.name][id]);- } else {- return payload.entities![entity.name][payload.result!];- }- } else {- return payload;- }- };-- // SELECTORS-- const getEntities = (state: State) => state.entities;- const getSettings = (state: State) => state.settings;-- // OBJECT SELECTORS-- const getEntityId = (- state: State,- props: { params?: { entityId?: EntityId }; entityId?: EntityId },- ): EntityId | undefined =>- (props.params && props.params.entityId) || props.entityId;-- const getObject = createCachedSelector(- [getEntities, getEntityId],- (entities: EntitiesState, entityId: EntityId | undefined) =>- denormalize(entityId, entity.schema, entities),- )((state: State, { entityId }: { entityId?: EntityId } = {}) =>- typeof entityId === "object"- ? JSON.stringify(entityId)- : entityId- ? String(entityId)- : "",- );-- // LIST SELECTORS-- const getEntityQueryId = (- state: any,- props: { entityQuery?: EntityQuery } | null | undefined,- ): string => getQueryKey(props?.entityQuery);-- const getEntityLists = createSelector([getEntities], (entities) => {- return entities[`${entity.name}_list`] as- | Record<string, { list?: EntityId[]; metadata?: unknown }>- | undefined;- });-- const getEntityList = createSelector(- [getEntityQueryId, getEntityLists],- (- entityQueryId: string,- lists:- | Record<string, { list?: EntityId[]; metadata?: unknown }>- | undefined,- ) => lists?.[entityQueryId],- );-- const getEntityIds = createSelector(- [getEntityList],- (entityList: { list?: EntityId[]; metadata?: unknown } | undefined) =>- entityList?.list,- );-- const getListMetadata = createSelector(- [getEntityList],- (entityList: { list?: EntityId[]; metadata?: unknown } | undefined) =>- entityList?.metadata,- );-- const getList = createCachedSelector(- [getEntities, getEntityIds, getSettings],- (- entities: EntitiesState,- entityIds: EntityId[] | undefined,- settings: unknown,- ) =>- entityIds &&- entityIds- .map((entityId) =>- entity.selectors.getObject({ entities, settings }, { entityId }),- )- .filter((e): e is EntityObject => e != null),- )((state: any, props: { entityQuery?: EntityQuery } | null | undefined) =>- props?.entityQuery ? JSON.stringify(props.entityQuery) : "",- );-- // REQUEST STATE SELECTORS-- type RequestStateEntry = {- loading?: boolean;- loaded?: boolean;- fetched?: boolean;- error?: unknown;- queryKey?: string;- queryPromise?: Promise<unknown>;- };-- const getStatePath = ({- entityId,- entityQuery,- }: { entityId?: EntityId; entityQuery?: EntityQuery } = {}): (- | string- | EntityId- )[] =>- entityId != null- ? getObjectStatePath(entityId)- : getListStatePath(entityQuery);-- const getRequestStatePath = ({- entityId,- entityQuery,- requestType = "fetch",- }: {- entityId?: EntityId;- entityQuery?: EntityQuery;- requestType?: string;- } = {}): string[] => [- "requests",- ...getStatePath({ entityId, entityQuery }).map(String),- requestType,- ];-- const defaultRequestState: RequestStateEntry = {};- const getRequestState = (- state: EntitiesState,- props?: {- entityId?: EntityId;- entityQuery?: EntityQuery;- requestType?: string;- },- ): RequestStateEntry =>- getIn(state, getRequestStatePath(props)) || defaultRequestState;-- const getLoading = createSelector(- [getRequestState],- (requestState: RequestStateEntry) => requestState.loading,- );- const getLoaded = createSelector(- [getRequestState],- (requestState: RequestStateEntry) => requestState.loaded,- );- const getFetched = createSelector(- [getRequestState],- (requestState: RequestStateEntry) => requestState.fetched,- );- const getError = createSelector(- [getRequestState],- (requestState: RequestStateEntry) => requestState.error,- );-- // createSelector/createCachedSelector attach cache methods; cast to the clean selector types- const defaultSelectors: Partial<EntitySelectors> = {- getEntityIds,- getList,- getObject,- getFetched,- getLoading,- getLoaded,- getError,- getListMetadata,- };- entity.selectors = {- ...defaultSelectors,- ...(def.selectors || {}),- ...(def.createSelectors ? def.createSelectors(defaultSelectors) : {}),- } as EntitySelectors;-- // REDUCERS-- const sliceReducer = handleEntities(- /^metabase\/entities\//,- entity.name,- def.reducer,- );-- const listReducer: EntityListReducer = (- state = {},- action: {- type: string;- error?: boolean;- payload?: Record<string, unknown>;- },- ) => {- if (action.error) {- return state;- }- if (action.type === FETCH_LIST_ACTION) {- if (action.payload && action.payload.result) {- const { entityQuery, metadata, result: list } = action.payload;- return {- ...state,- [getQueryKey(entityQuery)]: {- list,- metadata,- },- };- }- // NOTE: only add/remove from the "default" list (no entityQuery)- // TODO: just remove this entirely?- } else if (action.type === CREATE_ACTION && state[""]) {- return {- ...state,- "": (state[""] as EntityId[]).concat([- action.payload!.result as EntityId,- ]),- };- } else if (action.type === DELETE_ACTION && state[""]) {- return {- ...state,- "": (state[""] as EntityId[]).filter(- (id) => id !== action.payload!.result,- ),- };- }- return state;- };- entity.reducers = { slice: sliceReducer, list: listReducer };-- // REQUEST STATE REDUCER-- if (!entity.actionShouldInvalidateLists) {- entity.actionShouldInvalidateLists = (action: { type: string }) =>- action.type === CREATE_ACTION ||- action.type === DELETE_ACTION ||- action.type === UPDATE_ACTION ||- action.type === INVALIDATE_LISTS_ACTION;- }-- entity.requestsReducer = (- state: RequestsStateTree = {},- action: { type: string },- ) => {- if (entity.actionShouldInvalidateLists(action)) {- return requestsReducer(- state,- setRequestUnloaded(["entities", entity.name + "_list"]),- );- }- return state ?? {};- };-- // OBJECT WRAPPER-- if (!entity.wrapEntity) {- class EntityWrapper {- [key: string]: unknown;- _dispatch: AnyDispatch | null;-- constructor(- object: { id: EntityId },- dispatch: AnyDispatch | null = null,- ) {- Object.assign(this, object);- this._dispatch = dispatch;- }- }- // object actions- for (const [methodName, method] of Object.entries(entity.objectActions)) {- if (method) {- EntityWrapper.prototype[methodName] = function (- this: EntityWrapper,- ...args: unknown[]- ) {- if (this._dispatch) {- return this._dispatch(method(this, ...args));- } else {- return method(this, ...args);- }- };- }- }-- entity.wrapEntity = (- object: any,- dispatch: AnyDispatch | null = null,- ): any => new EntityWrapper(object, dispatch);- }-- // add container components and HOCs- // eslint-disable-next-line @typescript-eslint/no-require-imports -- dynamic require to avoid circular dependency- require("metabase/entities/containers").addEntityContainers(entity);-- // rtk can be defined as a function or a direct value- // make it a getter to callers don't need to worry about this detail- // and can still use definition.rtk- const rtk = entity.rtk;- Object.defineProperty(entity, "rtk", {- get() {- if (typeof rtk === "function") {- return rtk();- }- return rtk;- },- });-- return entity;-}--type EntitiesReducersMap = Record<string, EntitiesReducer | EntityListReducer>;--/**- * State shape produced by `combineReducers(reducersMap)`: each top-level key is- * either an entity slice or a `${name}_list` cache slice. See `EntitySliceValue`- * for the per-value type.- */-type EntitiesCombinedState = Record<string, Record<string, EntitySliceValue>>;--type CombinedEntities = {- entities: Record<string, Entity>;- reducers: EntitiesReducersMap;- reducer: Reducer<EntitiesCombinedState>;- requestsReducer: (- state: RequestsStateTree | undefined,- action: { type: string },- ) => RequestsStateTree;-};--/**- * Names of entities whose full `createEntity` definitions have been retired- * (their CRUD now lives in `metabase/api/*`), but whose normalized slice in- * `state.entities.<name>` still needs to receive updates dispatched via the- * `metabase/entities/UPDATE` action β typically because they appear nested in- * another entity's normalizr schema (e.g. measures inside a table's- * `query_metadata` response).- */-const RETIRED_ENTITY_NAMES = [- "collections",- "dashboards",- "databases",- "fields",- "measures",- "metrics",- "questions",- "schemas",- "segments",- "snippets",- "tables",-];--/**- * Custom slice reducers for retired entities whose normalized slice needs more- * than the default `handleEntities` merge β passed in by the caller (see- * `metabase/redux/entities`) to keep custom reducers out of this module and- * avoid circular imports.- */-export function combineEntities(- entities: Entity[],- retiredReducers: Record<string, EntitiesReducer> = {},-): CombinedEntities {- const entitiesMap: Record<string, Entity> = {};- const reducersMap: EntitiesReducersMap = {};-- for (const entity of entities) {- if (entity.name in entitiesMap) {- console.warn(`Entity with name ${entity.name} already exists!`);- } else {- entitiesMap[entity.name] = entity;- reducersMap[entity.name] = entity.reducers.slice;- reducersMap[`${entity.name}_list`] = entity.reducers.list;- }- }-- for (const name of RETIRED_ENTITY_NAMES) {- if (!(name in reducersMap)) {- reducersMap[name] = handleEntities(- /^metabase\/entities\//,- name,- retiredReducers[name],- );- }- }-- const combinedRequestsReducer = (- state: RequestsStateTree = {},- action: { type: string },- ): RequestsStateTree => {- let current = state;- for (const entity of entities) {- if (entity.requestsReducer) {- current = entity.requestsReducer(current, action);- }- }- return current;- };-- return {- entities: entitiesMap,- reducers: reducersMap,- reducer: combineReducers(reducersMap),- requestsReducer: combinedRequestsReducer,- };-}--// OBJECT ACTION DECORATORS--export const notify = (- opts: Record<string, unknown> = {},- subject: string,- verb: string,-) => merge({ notify: { subject, verb, undo: false } }, opts || {});--export const undo = (- opts: Record<string, unknown> = {},- subject: string,- verb: string,-) => merge({ notify: { subject, verb, undo: true } }, opts || {});--/**- * Structural minimum of an RTK Query endpoint descriptor. Concrete endpoints from- * RTK Query carry many extra properties (hooks, selectors, etc.) and concrete- * argument/result types β we only rely on `initiate` here.- */--type RTKEndpoint = { initiate: (request: any, options: any) => any };--export async function entityCompatibleQuery(- entityQuery: EntityQuery,- dispatch: AnyDispatch,- endpoint: RTKEndpoint,-- { forceRefetch = true } = {},-): Promise<any> {- const request = entityQuery === EMPTY_ENTITY_QUERY ? undefined : entityQuery;- const action = dispatch(endpoint.initiate(request, { forceRefetch }));-- try {- return await action.unwrap();- } finally {- action.unsubscribe?.();- }-}--type Thunk<R = unknown> = (- dispatch: Dispatch,- getState: () => State,-) => Promise<R> | R;--type ThunkCreator<TArgs extends unknown[], R = unknown> = (- ...args: TArgs-) => Thunk<R>;--export function withNormalize<TArgs extends unknown[]>(schema: Schema) {- return (thunkCreator: ThunkCreator<TArgs>) =>- (...args: TArgs) =>- async (dispatch: Dispatch, getState: () => State) =>- normalize(await thunkCreator(...args)(dispatch, getState), schema);-}--/**- * Decorator that tracks the state of a request action- */-export function withRequestState<TArgs extends unknown[]>(- getRequestStatePath: (...args: TArgs) => string[],- getQueryKey?: (...args: TArgs) => string | undefined,-) {- // thunk decorator:- return (thunkCreator: ThunkCreator<TArgs>) =>- // thunk creator:- (...args: TArgs) =>- // thunk:- async (dispatch: Dispatch, getState: () => State) => {- const statePath = getRequestStatePath(...args);- const queryKey = getQueryKey && getQueryKey(...args);- try {- dispatch(setRequestLoading(statePath, queryKey));-- const queryPromise = thunkCreator(...args)(dispatch, getState);- dispatch(- setRequestPromise(- statePath,- queryKey,- queryPromise as Promise<unknown>,- ),- );-- const result = await queryPromise;-- // Dispatch `setRequestLoaded` after clearing the call stack because- // we want to the actual data to be updated before we notify- // components that fetching the data is completed- setTimeout(() => dispatch(setRequestLoaded(statePath, queryKey)));-- return result;- } catch (error) {- console.error(`Request ${statePath.join(",")} failed:`, error);- dispatch(setRequestError(statePath, queryKey, error));- throw error;- }- };-}--/**- * Decorator that returns cached data if appropriate, otherwise calls the composed thunk.- * Also tracks request state using withRequestState- */-export function withCachedDataAndRequestState<TArgs extends unknown[]>(- getExistingStatePath: (...args: TArgs) => string[],- getRequestStatePath: (...args: TArgs) => string[],- getQueryKey?: (...args: TArgs) => string | undefined,-) {- return compose(- withCachedData(getExistingStatePath, getRequestStatePath, getQueryKey),- withRequestState(getRequestStatePath, getQueryKey),- );-}--type CachedRequestState = {- loading?: boolean;- loaded?: boolean;- queryKey?: string;- error?: { status?: number };- queryPromise?: Promise<unknown>;-};--type CachedOptions = {- useCachedForbiddenError?: boolean;- reload?: boolean | (() => void);- properties?: string[];-};--// NOTE: this should be used together with withRequestState, probably via withCachedDataAndRequestState-function withCachedData<TArgs extends unknown[]>(- getExistingStatePath: (...args: TArgs) => string[],- getRequestStatePath: (...args: TArgs) => string[],- getQueryKey?: (...args: TArgs) => string | undefined,-) {- // thunk decorator:- return (thunkCreator: ThunkCreator<TArgs>) =>- // thunk creator:- (...args: TArgs) =>- // thunk:- async function thunk(- dispatch: Dispatch,- getState: () => State,- ): Promise<unknown> {- const options = (args[args.length - 1] as CachedOptions) || {};- const { useCachedForbiddenError, reload, properties } = options;-- const existingStatePath = getExistingStatePath(...args);- const requestStatePath = ["requests", ...getRequestStatePath(...args)];- const newQueryKey = getQueryKey && getQueryKey(...args);- const existingData = getIn(getState(), existingStatePath);- const { loading, loaded, queryKey, error } =- (getIn(getState(), requestStatePath) as CachedRequestState) || {};-- // Avoid requesting data with permanently forbidden access- if (useCachedForbiddenError && error?.status === 403) {- throw error;- }-- const hasRequestedProperties =- properties &&- existingData &&- _.all(properties, (p: string) => existingData[p] !== undefined);-- // return existing data if- if (- // we don't want to reload- // the check is a workaround for EntityListLoader passing reload function to children- reload !== true &&- // reload if the query used to load an entity has changed even if it's already loaded- newQueryKey === queryKey- ) {- // and we have a non-error request state or have a list of properties that all exist on the object- if (loaded || hasRequestedProperties) {- return existingData;- } else if (loading) {- const requestState = getIn(getState(), requestStatePath) as- | CachedRequestState- | undefined;- const queryPromise = requestState?.queryPromise;-- if (queryPromise) {- // wait for current loading request to be resolved- await queryPromise;-- // need to wait for next tick to allow loaded request data to be processed and avoid loops- await delay(0);-- // retry this function after waited request gets resolved- return thunk(dispatch, getState);- }-- return existingData;- }- }-- return thunkCreator(...args)(dispatch, getState);- };-}--export type FetchDataArgs = {- dispatch: Dispatch;- getState: () => State;- requestStatePath: string[];- existingStatePath: string[];- queryKey?: string;- getData: () => Promise<unknown>;- reload?: boolean;- properties?: string[] | null;-};--// DEPRECATED-export const fetchData = async ({- dispatch,- getState,- requestStatePath,- existingStatePath,- queryKey,- getData,- reload = false,- properties = null,-}: FetchDataArgs): Promise<unknown> => {- const existingData = getIn(getState(), existingStatePath);-- // short circuit if we have loaded data, and we're given a list of required properties, and they all exist in the loaded data- if (- !reload &&- existingData &&- properties &&- _.all(properties, (p: string) => existingData[p] !== undefined)- ) {- return existingData;- }-- const statePath = requestStatePath.concat(["fetch"]);- try {- const requestState = getIn(getState(), ["requests", ...statePath]);- if (!requestState || requestState?.error || reload) {- dispatch(setRequestLoading(statePath, queryKey));-- const queryPromise = getData();- dispatch(setRequestPromise(statePath, queryKey, queryPromise));-- const data = await queryPromise;-- // NOTE Atte KeinΓ€nen 8/23/17:- // Dispatch `setRequestLoaded` after clearing the call stack because we want to the actual data to be updated- // before we notify components via `state.requests.fetches` that fetching the data is completed- setTimeout(() => dispatch(setRequestLoaded(statePath, queryKey)));-- return data;- }-- return existingData;- } catch (error) {- dispatch(setRequestError(statePath, queryKey, error));- console.error("fetchData error", error);- return existingData;- }-};--type UpdateDataArgs = {- dispatch: Dispatch;- getState: () => State;- requestStatePath: string[];- existingStatePath?: string[];- queryKey?: string;- dependentRequestStatePaths?: string[][];- putData: () => Promise<unknown>;-};--// DEPRECATED-export const updateData = async ({- dispatch,- getState,- requestStatePath,- existingStatePath,- queryKey,- dependentRequestStatePaths,- putData,-}: UpdateDataArgs): Promise<unknown> => {- const existingData = existingStatePath- ? getIn(getState(), existingStatePath)- : null;- const statePath = requestStatePath.concat(["update"]);- try {- dispatch(setRequestLoading(statePath, queryKey));-- const queryPromise = putData();- dispatch(setRequestPromise(statePath, queryKey, queryPromise));-- const data = await queryPromise;- dispatch(setRequestLoaded(statePath, queryKey));-- (dependentRequestStatePaths || []).forEach((path) =>- dispatch(setRequestUnloaded(path)),- );-- return data;- } catch (error) {- dispatch(setRequestError(statePath, queryKey, error));- console.error(error);- return existingData;- }-};diff --git a/frontend/src/metabase/entities/utils.unit.spec.ts b/frontend/src/metabase/entities/utils.unit.spec.tsdeleted file mode 100644index cfca2c1a20b..00000000000--- a/frontend/src/metabase/entities/utils.unit.spec.ts+++ /dev/null@@ -1,431 +0,0 @@-import { combineReducers, configureStore } from "@reduxjs/toolkit";--import { delay } from "__support__/utils";-import {- type RequestState,- type RequestsStateTree,- requestsReducer,-} from "metabase/redux/requests";-import type { Dispatch, State } from "metabase/redux/store";-import { createMockState } from "metabase/redux/store/mocks";-import { createMockRequestsState } from "metabase/redux/store/mocks/requests";--import {- combineEntities,- createEntity,- entityTypeForModel,- entityTypeForObject,- fetchData,- mergeEntities,- updateData,-} from "./utils";--describe("schemas", () => {- const MODEL_ENTITY_TYPE = [- { model: "card", entityType: "questions" },- { model: "dataset", entityType: "questions" },- { model: "dashboard", entityType: "dashboards" },- { model: "pulse", entityType: "pulses" },- { model: "collection", entityType: "collections" },- { model: "segment", entityType: "segments" },- { model: "metric", entityType: "questions" },- { model: "snippet", entityType: "snippets" },- { model: "snippetCollection", entityType: "snippetCollections" },- ];-- describe("entityTypeForModel", () => {- MODEL_ENTITY_TYPE.forEach((testCase) => {- const { model, entityType } = testCase;-- it(`returns "${entityType}" for "${model}" model`, () => {- expect(entityTypeForModel(model)).toBe(entityType);- });- });- });-- describe("entityTypeForObject", () => {- MODEL_ENTITY_TYPE.forEach((testCase) => {- const { model, entityType } = testCase;-- it(`returns "${entityType}" for "${model}" model`, () => {- expect(entityTypeForObject({ model })).toBe(entityType);- });- });-- it(`handles undefined object`, () => {- expect(entityTypeForObject()).toBe(undefined);- });- });-});--function getObject(id: number) {- return { id: id, name: `object${id}` };-}--function setup() {- const widgets = createEntity({- name: "widgets",- api: {- get: jest- .fn()- .mockImplementation(({ id }: { id: number }) => getObject(id)),- list: jest.fn().mockImplementation(() => [getObject(1), getObject(2)]),- },- });-- const entities = combineEntities([widgets]);-- const reducer = combineReducers({- entities: entities.reducer,- requests: (- state: RequestsStateTree | undefined,- action: { type: string; payload: Record<string, unknown> | undefined },- ) => requestsReducer(entities.requestsReducer(state, action), action),- });-- const initialState = {- entities: {- widgets: {- 1: { id: 1, name: "foo " },- 2: { id: 2, name: "bar" },- },- },- };-- const store = configureStore({- reducer,- preloadedState: initialState,- middleware: (getDefaultMiddleware) =>- getDefaultMiddleware({- immutableCheck: false,- serializableCheck: false,- }),- });-- return { widgets, store, initialState };-}--describe("entities", () => {- describe("getObject", () => {- it("should return an object", () => {- const { widgets, initialState } = setup();- expect(- widgets.selectors.getObject(initialState, { entityId: 1 }),- ).toEqual({ id: 1, name: "foo " });- });-- it("should cache the object", () => {- const { widgets, initialState } = setup();- const a1 = widgets.selectors.getObject(initialState, { entityId: 1 });- const a2 = widgets.selectors.getObject(initialState, { entityId: 1 });- expect(a1).toBe(a2);- });-- it("should cache multiple objects", () => {- const { widgets, initialState } = setup();- const a1 = widgets.selectors.getObject(initialState, { entityId: 1 });- const b1 = widgets.selectors.getObject(initialState, { entityId: 2 });- const a2 = widgets.selectors.getObject(initialState, { entityId: 1 });- const b2 = widgets.selectors.getObject(initialState, { entityId: 2 });- expect(a1).toBe(a2);- expect(b1).toBe(b2);- });- });-- describe("fetch", () => {- it("should fetch an entity", async () => {- const { widgets, store } = setup();- await store.dispatch(widgets.actions.fetch({ id: 3 }));- const object = widgets.selectors.getObject(store.getState(), {- entityId: 3,- });- expect(object).toEqual(getObject(3));- });- });-- describe("fetchList", () => {- it("should fetch a list of entities", async () => {- const { widgets, store } = setup();- await store.dispatch(widgets.actions.fetchList());- const objects = widgets.selectors.getList(store.getState());- expect(objects).toEqual([getObject(1), getObject(2)]);- });-- it("should not call the API when the results are cached", async () => {- const { widgets, store } = setup();- await store.dispatch(widgets.actions.fetchList());- expect(widgets.api.list).toHaveBeenCalledTimes(1);-- await store.dispatch(widgets.actions.fetchList());- expect(widgets.api.list).toHaveBeenCalledTimes(1);-- await store.dispatch(widgets.actions.fetchList({ query: "abc" }));- expect(widgets.api.list).toHaveBeenCalledTimes(2);-- await store.dispatch(widgets.actions.fetchList({ query: "abc" }));- expect(widgets.api.list).toHaveBeenCalledTimes(2);-- await store.dispatch(widgets.actions.fetchList());- expect(widgets.api.list).toHaveBeenCalledTimes(2);- });- });-- describe("mergeEntities", () => {- it("add an entity", () => {- expect(- mergeEntities<Record<string, { id: number; name: string }>>(- { actions: { id: 1, name: "foo" } },- { questions: { id: 2, name: "bar" } },- ),- ).toEqual({- actions: { id: 1, name: "foo" },- questions: { id: 2, name: "bar" },- });- });-- it("merge entity keys", () => {- expect(- mergeEntities<Record<string, Record<string, string | number>>>(- { actions: { id: 1, name: "foo", prop1: 123 } },- { actions: { id: 1, name: "bar", prop2: 456 } },- ),- ).toEqual({ actions: { id: 1, name: "bar", prop1: 123, prop2: 456 } });- });-- it("delete an entity", () => {- expect(- mergeEntities(- { databases: { id: 1 }, questions: { id: 2 } },- { questions: undefined },- ),- ).toEqual({ databases: { id: 1 } });- });- });-});--describe("Metadata", () => {- const getDefaultArgs = (- overrides: {- existingData?: string;- newData?: string;- requestState?: RequestState;- requestStateLoading?: RequestState;- requestStateLoaded?: RequestState;- requestStateError?: RequestState;- statePath?: string[];- statePathFetch?: string[];- statePathUpdate?: string[];- requestStatePath?: string[];- existingStatePath?: string[];- getState?: () => State;- dispatch?: Dispatch;- getData?: () => Promise<unknown>;- putData?: () => Promise<unknown>;- } = {},- ) => {- const existingData = overrides.existingData ?? "data";- const newData = overrides.newData ?? "new data";- const requestState = overrides.requestState;- const requestStateLoading = overrides.requestStateLoading ?? {- loading: true,- loaded: false,- fetched: false,- error: null,- _isRequestState: true as const,- };- const requestStateLoaded = overrides.requestStateLoaded ?? {- loading: false,- loaded: true,- fetched: true,- error: null,- _isRequestState: true as const,- };- const requestStateError = overrides.requestStateError ?? {- loading: false,- loaded: false,- fetched: false,- error: new Error("error"),- _isRequestState: true as const,- };- const statePath = overrides.statePath ?? ["test", "path"];- const statePathFetch =- overrides.statePathFetch ?? statePath.concat("fetch");- const statePathUpdate =- overrides.statePathUpdate ?? statePath.concat("update");- const requestStatePath = overrides.requestStatePath ?? [- "entities",- ...statePath,- ];- const existingStatePath = overrides.existingStatePath ?? statePath;- const getState =- overrides.getState ??- (() => ({- ...createMockState(),- requests: createMockRequestsState({- entities: {- test: {- path: requestState- ? { fetch: requestState, update: requestState }- : {},- },- },- }),- test: { path: existingData },- }));- const dispatch = overrides.dispatch ?? jest.fn();- const getData = overrides.getData ?? (() => Promise.resolve(newData));- const putData = overrides.putData ?? (() => Promise.resolve(newData));-- return {- dispatch,- getState,- requestStatePath,- existingStatePath,- getData,- putData,- // passthrough args constants- existingData,- newData,- requestState,- requestStateLoading,- requestStateLoaded,- requestStateError,- statePath,- statePathFetch,- statePathUpdate,- };- };-- const args = getDefaultArgs({});-- describe("fetchData()", () => {- it("should return new data if request hasn't been made", async () => {- const argsDefault = getDefaultArgs({});- const data = await fetchData(argsDefault);- await delay(10);-- expect(argsDefault.dispatch).toHaveBeenCalledTimes(3);-- expect(argsDefault.dispatch).toHaveBeenCalledWith(- expect.objectContaining({- type: "metabase/requests/SET_REQUEST_LOADING",- }),- );- expect(argsDefault.dispatch).toHaveBeenCalledWith(- expect.objectContaining({- type: "metabase/requests/SET_REQUEST_PROMISE",- }),- );- expect(argsDefault.dispatch).toHaveBeenCalledWith(- expect.objectContaining({- type: "metabase/requests/SET_REQUEST_LOADED",- }),- );-- expect(data).toEqual(args.newData);- });-- it("should return existing data if request has been made", async () => {- const argsLoading = getDefaultArgs({- requestState: args.requestStateLoading,- });- const dataLoading = await fetchData(argsLoading);- expect(argsLoading.dispatch).toHaveBeenCalledTimes(0);- expect(dataLoading).toEqual(args.existingData);-- const argsLoaded = getDefaultArgs({- requestState: args.requestStateLoaded,- });- const dataLoaded = await fetchData(argsLoaded);- expect(argsLoaded.dispatch).toHaveBeenCalledTimes(0);- expect(dataLoaded).toEqual(args.existingData);- });-- it("should return new data if previous request ended in error", async () => {- const argsError = getDefaultArgs({- requestState: args.requestStateError,- });- const dataError = await fetchData(argsError);- await delay(10);-- expect(argsError.dispatch).toHaveBeenCalledTimes(3);-- expect(argsError.dispatch).toHaveBeenCalledWith(- expect.objectContaining({- type: "metabase/requests/SET_REQUEST_LOADING",- }),- );- expect(argsError.dispatch).toHaveBeenCalledWith(- expect.objectContaining({- type: "metabase/requests/SET_REQUEST_PROMISE",- }),- );- expect(argsError.dispatch).toHaveBeenCalledWith(- expect.objectContaining({- type: "metabase/requests/SET_REQUEST_LOADED",- }),- );-- expect(dataError).toEqual(args.newData);- });-- // FIXME: this seems to make jasmine ignore the rest of the tests- // is an exception bubbling up from fetchData? why?- // how else to test return value in the catch case?- it("should return existing data if request fails", async () => {- const argsFail = getDefaultArgs({- getData: () => Promise.reject("error"),- });-- try {- const dataFail = await fetchData(argsFail);- expect(argsFail.dispatch).toHaveBeenCalledTimes(2);- expect(dataFail).toEqual(args.existingData);- } catch (error) {- return;- }- });- });-- describe("updateData()", () => {- it("should return new data regardless of previous request state", async () => {- const argsDefault = getDefaultArgs({});- const data = await updateData(argsDefault);- expect(argsDefault.dispatch).toHaveBeenCalledTimes(3);- expect(data).toEqual(args.newData);-- const argsLoading = getDefaultArgs({- requestState: args.requestStateLoading,- });- const dataLoading = await updateData(argsLoading);- expect(argsLoading.dispatch).toHaveBeenCalledTimes(3);- expect(dataLoading).toEqual(args.newData);-- const argsLoaded = getDefaultArgs({- requestState: args.requestStateLoaded,- });- const dataLoaded = await updateData(argsLoaded);- expect(argsLoaded.dispatch).toHaveBeenCalledTimes(3);- expect(dataLoaded).toEqual(args.newData);-- const argsError = getDefaultArgs({- requestState: args.requestStateError,- });- const dataError = await updateData(argsError);- expect(argsError.dispatch).toHaveBeenCalledTimes(3);- expect(dataError).toEqual(args.newData);- });-- it("should return existing data if request fails", async () => {- const argsFail = getDefaultArgs({- putData: () => {- throw new Error("test");- },- });- const data = await updateData(argsFail);- await delay(10);- expect(argsFail.dispatch).toHaveBeenCalledTimes(2);- expect(data).toEqual(args.existingData);- });- });-});diff --git a/frontend/src/metabase/plugins/index.ts b/frontend/src/metabase/plugins/index.tsindex b8f288d8a90..ca3d6afafa9 100644--- a/frontend/src/metabase/plugins/index.ts+++ b/frontend/src/metabase/plugins/index.ts@@ -68,7 +68,6 @@ export {type SdkIframeEmbedSetupModalInitialState,} from "./oss/embedding-iframe-sdk-setup";export { PLUGIN_EMBEDDING_SDK } from "./oss/embedding-sdk";-export { PLUGIN_ENTITIES } from "./oss/entities";export {PLUGIN_LIBRARY,type CollectionPermissionsModalProps,@@ -186,7 +185,6 @@ import { reinitialize as reinitializeEmbedding } from "./oss/embedding";import { reinitialize as reinitializeEmbeddingIframeSdk } from "./oss/embedding-iframe-sdk";import { reinitialize as reinitializeEmbeddingIframeSdkSetup } from "./oss/embedding-iframe-sdk-setup";import { reinitialize as reinitializeEmbeddingSdk } from "./oss/embedding-sdk";-import { reinitialize as reinitializeEntities } from "./oss/entities";import { reinitialize as reinitializeLibrary } from "./oss/library";import { reinitialize as reinitializeMetabot } from "./oss/metabot";import { reinitialize as reinitializeModelPersistence } from "./oss/model-persistence";@@ -230,7 +228,6 @@ export function reinitialize() {reinitializeEmbeddingIframeSdk();reinitializeEmbeddingIframeSdkSetup();reinitializeEmbeddingSdk();- reinitializeEntities();reinitializeLibrary();reinitializeMetabot();reinitializeModelPersistence();diff --git a/frontend/src/metabase/plugins/oss/entities.ts b/frontend/src/metabase/plugins/oss/entities.tsdeleted file mode 100644index 660d6e46cb9..00000000000--- a/frontend/src/metabase/plugins/oss/entities.ts+++ /dev/null@@ -1,12 +0,0 @@-const getDefaultPluginEntities = () => ({- entities: {} as Record<string, any>,-});--export const PLUGIN_ENTITIES = getDefaultPluginEntities();--/**- * @internal Do not call directly. Use the main reinitialize function from metabase/plugins instead.- */-export function reinitialize() {- Object.assign(PLUGIN_ENTITIES, getDefaultPluginEntities());-}diff --git a/frontend/src/metabase/plugins/oss/library.ts b/frontend/src/metabase/plugins/oss/library.tsindex 485ba0d01b3..b144ed556fe 100644--- a/frontend/src/metabase/plugins/oss/library.ts+++ b/frontend/src/metabase/plugins/oss/library.ts@@ -2,12 +2,12 @@ import type { BaseQueryFn, QueryDefinition } from "@reduxjs/toolkit/query";import type { ComponentType, ReactNode } from "react";import type { TagType } from "metabase/api/tags";+import type { UseQuery } from "metabase/api/types/rtk";import type {OmniPickerCollectionItem,OmniPickerItem,} from "metabase/common/components/Pickers/EntityPicker/types";import type { MiniPickerCollectionFolderItem } from "metabase/common/components/Pickers/MiniPicker/types";-import type { UseQuery } from "metabase/entities/containers/rtk-query/types/rtk";import { PluginPlaceholder } from "metabase/plugins/components/PluginPlaceholder";import type {Collection,diff --git a/frontend/src/metabase/plugins/oss/remote-sync.ts b/frontend/src/metabase/plugins/oss/remote-sync.tsindex ce4fe2c32ee..a9ffd28ecd8 100644--- a/frontend/src/metabase/plugins/oss/remote-sync.ts+++ b/frontend/src/metabase/plugins/oss/remote-sync.ts@@ -6,9 +6,9 @@ import type {import type { ComponentType, ReactNode } from "react";import type { TagType } from "metabase/api/tags";+import type { UseQuery } from "metabase/api/types/rtk";import type { CollectionTreeItem } from "metabase/collections/utils";import type { ITreeNodeItem } from "metabase/common/components/tree/types";-import type { UseQuery } from "metabase/entities/containers/rtk-query/types/rtk";import type {GitSyncSetupMenuItemProps,SyncedCollectionsSidebarSectionProps,diff --git a/frontend/src/metabase/query_builder/actions/core/core.ts b/frontend/src/metabase/query_builder/actions/core/core.tsindex 033ba918b83..172e50b28ca 100644--- a/frontend/src/metabase/query_builder/actions/core/core.ts+++ b/frontend/src/metabase/query_builder/actions/core/core.ts@@ -7,11 +7,11 @@ import {revisionApi,} from "metabase/api";import { listTag } from "metabase/api/tags";+import { runRtkEndpoint } from "metabase/api/utils/run-rtk-endpoint";import {cardIsEquivalent,cardQueryIsEquivalent,} from "metabase/common/utils/card";-import { entityCompatibleQuery } from "metabase/entities/utils";import { loadMetadataForCard } from "metabase/questions/actions";import { createThunkAction } from "metabase/redux";import { openUrl } from "metabase/redux/app";@@ -63,7 +63,7 @@ export const softReloadCard = createThunkAction(SOFT_RELOAD_CARD, () => {return async (dispatch, getState) => {const outdatedCard = getCard(getState());- return entityCompatibleQuery(+ return runRtkEndpoint({ id: outdatedCard?.id },dispatch,cardApi.endpoints.getCard,@@ -82,7 +82,7 @@ export const reloadCard = createThunkAction(RELOAD_CARD, () => {return;}- const card = await entityCompatibleQuery(+ const card = await runRtkEndpoint({ id: outdatedQuestion.id() },dispatch,cardApi.endpoints.getCard,@@ -356,7 +356,7 @@ export const revertToRevision = createThunkAction(REVERT_CARD_TO_REVISION,(cardId, revision) => {return async (dispatch) => {- await entityCompatibleQuery(+ await runRtkEndpoint({id: cardId,entity: "card",diff --git a/frontend/src/metabase/query_builder/actions/core/initializeQB.ts b/frontend/src/metabase/query_builder/actions/core/initializeQB.tsindex e497b4ce017..a461acdf57a 100644--- a/frontend/src/metabase/query_builder/actions/core/initializeQB.ts+++ b/frontend/src/metabase/query_builder/actions/core/initializeQB.ts@@ -2,12 +2,12 @@ import type { LocationDescriptorObject } from "history";import { replace } from "react-router-redux";import { cardApi, snippetApi } from "metabase/api";+import { runRtkEndpoint } from "metabase/api/utils/run-rtk-endpoint";import {cardIsEquivalent,deserializeCard,parseHash,} from "metabase/common/utils/card";-import { entityCompatibleQuery } from "metabase/entities/utils";import {getIsEditingInDashboard,getNotebookNativePreviewSidebarWidth,@@ -235,7 +235,7 @@ export async function updateTemplateTagNames(await Promise.all(query.referencedQuestionIds().map(async (id) => {try {- return await entityCompatibleQuery(+ return await runRtkEndpoint({ id, ignore_error: true },dispatch,cardApi.endpoints.getCard,diff --git a/frontend/src/metabase/query_builder/actions/native.ts b/frontend/src/metabase/query_builder/actions/native.tsindex dcda07e0279..2c75c38830e 100644--- a/frontend/src/metabase/query_builder/actions/native.ts+++ b/frontend/src/metabase/query_builder/actions/native.ts@@ -1,7 +1,7 @@import { createAction } from "redux-actions";import { cardApi } from "metabase/api";-import { entityCompatibleQuery } from "metabase/entities/utils";+import { runRtkEndpoint } from "metabase/api/utils/run-rtk-endpoint";import { createThunkAction } from "metabase/redux";import { updateUserSetting } from "metabase/redux/settings";import type { Dispatch, GetState } from "metabase/redux/store";@@ -57,7 +57,7 @@ export const openDataReferenceAtQuestion = createThunkAction(// forceRefetch: false so a permanently-forbidden card (403) is served from// RTK Query's cache instead of re-hitting /api/card/:id on every open, matching// the former `useCachedForbiddenError` behavior.- const card = await entityCompatibleQuery(+ const card = await runRtkEndpoint({ id, ignore_error: true },dispatch,cardApi.endpoints.getCard,diff --git a/frontend/src/metabase/query_builder/actions/object-detail.ts b/frontend/src/metabase/query_builder/actions/object-detail.tsindex b5543617c20..cf9bd20ef23 100644--- a/frontend/src/metabase/query_builder/actions/object-detail.ts+++ b/frontend/src/metabase/query_builder/actions/object-detail.ts@@ -1,7 +1,7 @@import _ from "underscore";import { datasetApi } from "metabase/api";-import { entityCompatibleQuery } from "metabase/entities/utils";+import { runRtkEndpoint } from "metabase/api/utils/run-rtk-endpoint";import { createThunkAction } from "metabase/redux";import { RESET_ROW_ZOOM } from "metabase/redux/query-builder";import type { Dispatch, GetState } from "metabase/redux/store";@@ -156,7 +156,7 @@ export const loadObjectDetailFKReferences = createThunkAction(};try {- const result = await entityCompatibleQuery(+ const result = await runRtkEndpoint(finalCard,dispatch,datasetApi.endpoints.getAdhocQuery,diff --git a/frontend/src/metabase/query_builder/components/template_tags/TagEditorParam.tsx b/frontend/src/metabase/query_builder/components/template_tags/TagEditorParam.tsxindex 746fd5be575..a6558d9f1db 100644--- a/frontend/src/metabase/query_builder/components/template_tags/TagEditorParam.tsx+++ b/frontend/src/metabase/query_builder/components/template_tags/TagEditorParam.tsx@@ -3,7 +3,7 @@ import { t } from "ttag";import _ from "underscore";import { fieldApi } from "metabase/api";-import { entityCompatibleQuery } from "metabase/entities/utils";+import { runRtkEndpoint } from "metabase/api/utils/run-rtk-endpoint";import { TemporalUnitSettings } from "metabase/parameters/components/TemporalUnitSettings";import { ValuesSourceSettings } from "metabase/parameters/components/ValuesSourceSettings";import { isSingleOrMultiSelectable } from "metabase/parameters/utils/parameter-type";@@ -101,7 +101,7 @@ const mapDispatchToProps = (): DispatchProps => {return {async fetchField(fieldId, force) {- const field = await entityCompatibleQuery(+ const field = await runRtkEndpoint({ id: fieldId },dispatch,fieldApi.endpoints.getField,@@ -109,7 +109,7 @@ const mapDispatchToProps = ();const remapId = field?.dimensions?.[0]?.human_readable_field_id;if (remapId != null) {- await entityCompatibleQuery(+ await runRtkEndpoint({ id: remapId },dispatch,fieldApi.endpoints.getField,diff --git a/frontend/src/metabase/query_builder/components/view/View/View/View.jsx b/frontend/src/metabase/query_builder/components/view/View/View/View.jsxindex a3bdd8a534c..b579af731fe 100644--- a/frontend/src/metabase/query_builder/components/view/View/View/View.jsx+++ b/frontend/src/metabase/query_builder/components/view/View/View/View.jsx@@ -8,6 +8,7 @@ import _ from "underscore";import { Api, cardApi } from "metabase/api";import { listTag } from "metabase/api/tags";+import { runRtkEndpoint } from "metabase/api/utils/run-rtk-endpoint";import { deletePermanently } from "metabase/archive/actions";import { getEntityTypeFromCardType } from "metabase/collections/utils";import { ExplicitSize } from "metabase/common/components/ExplicitSize";@@ -16,7 +17,6 @@ import { Toaster } from "metabase/common/components/Toaster";import { useSetCollection } from "metabase/common/hooks";import CS from "metabase/css/core/index.css";import QueryBuilderS from "metabase/css/query_builder.module.css";-import { entityCompatibleQuery } from "metabase/entities/utils";import {rememberLastUsedDatabase,runOrCancelQuestionOrSelectedQuery,@@ -304,7 +304,7 @@ const mapDispatchToProps = (dispatch) => ({},onDeletePermanently: (id) => {const deleteAction = (dispatch) =>- entityCompatibleQuery(id, dispatch, cardApi.endpoints.deleteCard);+ runRtkEndpoint(id, dispatch, cardApi.endpoints.deleteCard);dispatch(deletePermanently(deleteAction));},runQuery: () => {diff --git a/frontend/src/metabase/querying/common/components/DataSelector/DataSelector.jsx b/frontend/src/metabase/querying/common/components/DataSelector/DataSelector.jsxindex 43cbbb4b4c1..719ad250309 100644--- a/frontend/src/metabase/querying/common/components/DataSelector/DataSelector.jsx+++ b/frontend/src/metabase/querying/common/components/DataSelector/DataSelector.jsx@@ -13,10 +13,10 @@ import {useListDatabasesQuery,useSearchQuery,} from "metabase/api";+import { runRtkEndpoint } from "metabase/api/utils/run-rtk-endpoint";import { EmptyState } from "metabase/common/components/EmptyState";import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";import CS from "metabase/css/core/index.css";-import { entityCompatibleQuery } from "metabase/entities/utils";import { connect } from "metabase/redux";import { fetchTableMetadata } from "metabase/redux/tables";import { getMetadata } from "metabase/selectors/metadata";@@ -1198,7 +1198,7 @@ const DataSelector = _.compose(},(dispatch) => ({fetchDatabases: (databaseQuery) =>- entityCompatibleQuery(+ runRtkEndpoint({ ...databaseQuery, "can-query": true },dispatch,databaseApi.endpoints.listDatabases,@@ -1206,7 +1206,7 @@ const DataSelector = _.compose(),fetchFields: (tableId) => dispatch(fetchTableMetadata({ id: tableId })),fetchQuestion: (id) =>- entityCompatibleQuery(+ runRtkEndpoint({ id: getQuestionIdFromVirtualTableId(id) },dispatch,cardApi.endpoints.getCard,diff --git a/frontend/src/metabase/questions/actions.ts b/frontend/src/metabase/questions/actions.tsindex b86e490da20..027252b6983 100644--- a/frontend/src/metabase/questions/actions.ts+++ b/frontend/src/metabase/questions/actions.ts@@ -1,5 +1,5 @@import { cardApi, datasetApi } from "metabase/api";-import { entityCompatibleQuery } from "metabase/entities/utils";+import { runRtkEndpoint } from "metabase/api/utils/run-rtk-endpoint";import type { Dispatch } from "metabase/redux/store";import { fetchTableMetadata } from "metabase/redux/tables";import type { Card, TableId, UnsavedCard } from "metabase-types/api";@@ -25,14 +25,14 @@ export const loadMetadataForCard =) =>async (dispatch: Dispatch) => {if (isSavedCard(card)) {- return entityCompatibleQuery(+ return runRtkEndpoint(token ?? card.id,dispatch,cardApi.endpoints.getCardQueryMetadata,{ forceRefetch: false },);} else if (card.dataset_query.database != null) {- return entityCompatibleQuery(+ return runRtkEndpoint({...card.dataset_query,...(!!token && { token }),diff --git a/frontend/src/metabase/questions/components/MoveCardModal/MoveCardModal.tsx b/frontend/src/metabase/questions/components/MoveCardModal/MoveCardModal.tsxindex c8a0d863422..04374a1efdf 100644--- a/frontend/src/metabase/questions/components/MoveCardModal/MoveCardModal.tsx+++ b/frontend/src/metabase/questions/components/MoveCardModal/MoveCardModal.tsx@@ -15,8 +15,8 @@ import { ConfirmModal } from "metabase/common/components/ConfirmModal";import { DashboardName } from "metabase/common/components/DashboardName";import type { OmniPickerCollectionItem } from "metabase/common/components/Pickers";import { MoveModal } from "metabase/common/components/Pickers";-import { INJECT_RTK_QUERY_QUESTION_VALUE } from "metabase/entities/questions-reducer";import { useDispatch } from "metabase/redux";+import { INJECT_RTK_QUERY_QUESTION_VALUE } from "metabase/redux/entities/questions-reducer";import { API_UPDATE_QUESTION } from "metabase/redux/query-builder";import { addUndo } from "metabase/redux/undo";import { Box, Icon, Radio, Title } from "metabase/ui";diff --git a/frontend/src/metabase/reducers-common.ts b/frontend/src/metabase/reducers-common.tsindex 4b6aad48b27..48899b7d56f 100644--- a/frontend/src/metabase/reducers-common.ts+++ b/frontend/src/metabase/reducers-common.ts@@ -12,7 +12,7 @@ import { reducer as auth } from "metabase/redux/auth";import { reducer as downloads } from "metabase/redux/downloads";import { embed } from "metabase/redux/embed";import { reducer as embeddingDataPicker } from "metabase/redux/embedding-data-picker";-import entities, { enhanceRequestsReducer } from "metabase/redux/entities";+import entities from "metabase/redux/entities";import { requestsReducer } from "metabase/redux/requests";import { settings } from "metabase/redux/settings";import { modal } from "metabase/redux/ui";@@ -28,8 +28,7 @@ export const commonReducers = {embed,embeddingDataPicker,currentUser,- // "entities" framework needs control over "requests" state- requests: enhanceRequestsReducer(requestsReducer),+ requests: requestsReducer,settings,undo,entities,diff --git a/frontend/src/metabase/redux/cards.ts b/frontend/src/metabase/redux/cards.tsindex 05a0d3c7eb7..cf7b88a0091 100644--- a/frontend/src/metabase/redux/cards.ts+++ b/frontend/src/metabase/redux/cards.ts@@ -1,8 +1,8 @@import _ from "underscore";import { cardApi } from "metabase/api";-import { INJECT_RTK_QUERY_QUESTION_VALUE } from "metabase/entities/questions-reducer";-import { entityCompatibleQuery } from "metabase/entities/utils";+import { runRtkEndpoint } from "metabase/api/utils/run-rtk-endpoint";+import { INJECT_RTK_QUERY_QUESTION_VALUE } from "metabase/redux/entities/questions-reducer";import type { Dispatch } from "metabase/redux/store";import type { Card } from "metabase-types/api";@@ -79,7 +79,7 @@ export const createQuestionCard =? { dashboard_id, dashboard_tab_id }: { collection_id };- const card: Card = await entityCompatibleQuery(+ const card: Card = await runRtkEndpoint({ ...rest, ...destination },dispatch,cardApi.endpoints.createCard,@@ -99,7 +99,7 @@ export const createQuestionCard =export const updateQuestionCard =(request: object) =>async (dispatch: Dispatch): Promise<Card> => {- const card: Card = await entityCompatibleQuery(+ const card: Card = await runRtkEndpoint(pickWritable(request),dispatch,cardApi.endpoints.updateCard,diff --git a/frontend/src/metabase/redux/databases.ts b/frontend/src/metabase/redux/databases.tsindex e872f62d655..83e57559783 100644--- a/frontend/src/metabase/redux/databases.ts+++ b/frontend/src/metabase/redux/databases.ts@@ -1,7 +1,7 @@import _ from "underscore";import { databaseApi } from "metabase/api";-import { entityCompatibleQuery } from "metabase/entities/utils";+import { runRtkEndpoint } from "metabase/api/utils/run-rtk-endpoint";import { updateMetadata } from "metabase/redux/metadata-typed";import type { Dispatch } from "metabase/redux/store";import { DatabaseSchema } from "metabase/schema";@@ -45,7 +45,7 @@ export const createDatabase = function (inputDatabase: DatabaseData) {return async function (dispatch: Dispatch) {try {- const savedDatabase = await entityCompatibleQuery(+ const savedDatabase = await runRtkEndpoint(database,dispatch,databaseApi.endpoints.createDatabase,diff --git a/frontend/src/metabase/redux/entities.js b/frontend/src/metabase/redux/entities.jsdeleted file mode 100644index 0ac55f884f8..00000000000--- a/frontend/src/metabase/redux/entities.js+++ /dev/null@@ -1,27 +0,0 @@-import * as entitiesMap from "metabase/entities";-import { questionsReducer } from "metabase/entities/questions-reducer";-import { tablesReducer } from "metabase/entities/tables-reducer";-import { combineEntities } from "metabase/entities/utils";-import { PLUGIN_ENTITIES } from "metabase/plugins";--// `metabase/entities` no longer exports any entities, so guard against-// non-entity values (e.g. interop artifacts from the empty barrel) reaching-// combineEntities.-const entitiesArray = Object.values({- ...entitiesMap,- ...PLUGIN_ENTITIES.entities,-}).filter((entity) => entity?.reducers != null);--export const { entities, reducer, requestsReducer } = combineEntities(- entitiesArray,- { questions: questionsReducer, tables: tablesReducer },-);-// eslint-disable-next-line import/no-default-export -- deprecated usage-export default reducer;--export const enhanceRequestsReducer = (originalRequestsReducer) => {- return (state, action) =>- originalRequestsReducer(requestsReducer(state, action), action);-};--(window.Metabase = window.Metabase || {}).entities = entities;diff --git a/frontend/src/metabase/redux/entities/index.ts b/frontend/src/metabase/redux/entities/index.tsnew file mode 100644index 00000000000..4b1b2237929--- /dev/null+++ b/frontend/src/metabase/redux/entities/index.ts@@ -0,0 +1,94 @@+import { type Reducer, combineReducers } from "@reduxjs/toolkit";+import { getIn } from "icepick";++import { questionsReducer } from "./questions-reducer";+import { tablesReducer } from "./tables-reducer";++type SliceState = Record<string, unknown>;+type SliceAction = { type: string; payload?: any };+type SliceReducer = Reducer<SliceState>;++/**+ * Slices held under `state.entities.<name>`. These used to be wired up by the+ * (now-removed) entity framework via `createEntity`; the slices themselves+ * still exist because `getMetadata` in `metabase/selectors/metadata.ts` reads+ * directly from them. RTK Query endpoints populate the slices by dispatching+ * `metabase/entities/UPDATE` (see `hydrateMetadataStore`).+ */+const ENTITY_SLICE_NAMES = [+ "collections",+ "dashboards",+ "databases",+ "fields",+ "measures",+ "metrics",+ "questions",+ "schemas",+ "segments",+ "snippets",+ "tables",+] as const;++const ACTION_PATTERN = /^metabase\/entities\//;++/**+ * Merges newEntities into entities, deleting keys whose value is nullish.+ * Existing entries are shallow-merged so partial entities don't overwrite+ * full ones.+ */+function mergeEntities(+ entities: SliceState,+ newEntities: Record<string, unknown>,+): SliceState {+ const result = { ...entities };+ for (const id of Object.keys(newEntities)) {+ const entry = newEntities[id];+ if (entry == null) {+ delete result[id];+ } else {+ result[id] = {+ ...((result[id] as Record<string, unknown>) ?? {}),+ ...(entry as Record<string, unknown>),+ };+ }+ }+ return result;+}++/**+ * Build the reducer for a single `state.entities.<name>` slice. It merges any+ * `payload.entities.<name>` from `metabase/entities/*` actions and then runs+ * the optional custom reducer on top.+ */+function makeSliceReducer(+ sliceName: string,+ customReducer?: SliceReducer,+): SliceReducer {+ return (state = {}, action: SliceAction) => {+ let nextState = state;+ const entities = getIn(action, ["payload", "entities", sliceName]) as+ | Record<string, unknown>+ | undefined;+ if (ACTION_PATTERN.test(action.type) && entities) {+ nextState = mergeEntities(nextState, entities);+ }+ return customReducer ? customReducer(nextState, action) : nextState;+ };+}++const customReducers: Partial<Record<string, SliceReducer>> = {+ questions: questionsReducer as SliceReducer,+ tables: tablesReducer as SliceReducer,+};++const sliceReducers = Object.fromEntries(+ ENTITY_SLICE_NAMES.map((name) => [+ name,+ makeSliceReducer(name, customReducers[name]),+ ]),+) as Record<(typeof ENTITY_SLICE_NAMES)[number], SliceReducer>;++export const reducer = combineReducers(sliceReducers);++// eslint-disable-next-line import/no-default-export -- deprecated usage+export default reducer;diff --git a/frontend/src/metabase/redux/entities/index.unit.spec.ts b/frontend/src/metabase/redux/entities/index.unit.spec.tsnew file mode 100644index 00000000000..6756b39ef08--- /dev/null+++ b/frontend/src/metabase/redux/entities/index.unit.spec.ts@@ -0,0 +1,151 @@+import { SOFT_RELOAD_CARD } from "metabase/redux/query-builder";++import { reducer } from "./index";++const UPDATE = "metabase/entities/UPDATE";++describe("entities reducer", () => {+ it("initializes every slice to an empty object", () => {+ const state = reducer(undefined, { type: "@@INIT" });++ expect(state).toEqual({+ collections: {},+ dashboards: {},+ databases: {},+ fields: {},+ measures: {},+ metrics: {},+ questions: {},+ schemas: {},+ segments: {},+ snippets: {},+ tables: {},+ });+ });++ describe(UPDATE, () => {+ it("writes new entries into the matching slice", () => {+ const state = reducer(undefined, {+ type: UPDATE,+ payload: {+ entities: {+ databases: { 1: { id: 1, name: "DB" } },+ },+ },+ });++ expect(state.databases).toEqual({ 1: { id: 1, name: "DB" } });+ });++ it("shallow-merges partial entries so existing fields are preserved", () => {+ const initial = reducer(undefined, {+ type: UPDATE,+ payload: {+ entities: {+ fields: { 7: { id: 7, name: "Full", base_type: "type/Text" } },+ },+ },+ });++ const next = reducer(initial, {+ type: UPDATE,+ payload: {+ entities: {+ fields: { 7: { id: 7, semantic_type: "type/Category" } },+ },+ },+ });++ expect(next.fields[7]).toEqual({+ id: 7,+ name: "Full",+ base_type: "type/Text",+ semantic_type: "type/Category",+ });+ });++ it("deletes entries whose payload value is nullish", () => {+ const initial = reducer(undefined, {+ type: UPDATE,+ payload: {+ entities: {+ tables: { 1: { id: 1, name: "Keep" }, 2: { id: 2, name: "Drop" } },+ },+ },+ });++ const next = reducer(initial, {+ type: UPDATE,+ payload: { entities: { tables: { 2: null } } },+ });++ expect(next.tables).toEqual({ 1: { id: 1, name: "Keep" } });+ });++ it("merges into multiple slices from a single action", () => {+ const next = reducer(undefined, {+ type: UPDATE,+ payload: {+ entities: {+ databases: { 1: { id: 1 } },+ tables: { 2: { id: 2 } },+ fields: { 3: { id: 3 } },+ },+ },+ });++ expect(next.databases).toEqual({ 1: { id: 1 } });+ expect(next.tables).toEqual({ 2: { id: 2 } });+ expect(next.fields).toEqual({ 3: { id: 3 } });+ });++ it("ignores slices that are not part of the entities map", () => {+ const next = reducer(undefined, {+ type: UPDATE,+ payload: { entities: { unknownSlice: { 1: { id: 1 } } } },+ });++ expect(next).not.toHaveProperty("unknownSlice");+ });+ });++ it("ignores actions outside the metabase/entities/* namespace", () => {+ const initial = reducer(undefined, {+ type: UPDATE,+ payload: { entities: { databases: { 1: { id: 1, name: "DB" } } } },+ });++ const next = reducer(initial, {+ type: "metabase/other/UPDATE",+ payload: { entities: { databases: { 1: { id: 1, name: "Renamed" } } } },+ });++ expect(next.databases).toBe(initial.databases);+ });++ describe("custom slice reducers", () => {+ it("runs the questions custom reducer after merging entities", () => {+ const merged = reducer(undefined, {+ type: UPDATE,+ payload: {+ entities: {+ questions: { 1: { id: 1, moderated_status: null } },+ },+ },+ });++ const next = reducer(merged, {+ type: SOFT_RELOAD_CARD,+ payload: {+ id: 1,+ moderation_reviews: [{ status: "verified", most_recent: true }],+ },+ });++ expect(next.questions[1]).toMatchObject({+ id: 1,+ moderated_status: "verified",+ });+ });+ });+});diff --git a/frontend/src/metabase/entities/questions-reducer.ts b/frontend/src/metabase/redux/entities/questions-reducer.tssimilarity index 69%rename from frontend/src/metabase/entities/questions-reducer.tsrename to frontend/src/metabase/redux/entities/questions-reducer.tsindex a8357874d7e..323c67e4759 100644--- a/frontend/src/metabase/entities/questions-reducer.ts+++ b/frontend/src/metabase/redux/entities/questions-reducer.ts@@ -15,15 +15,16 @@ type ReducerAction = { type: string; payload?: any };/*** Reducer for the `state.entities.questions` slice.*- * The `questions` entity has been removed from the entity framework (its CRUD- * now lives in `metabase/api/card`), but the normalized slice still needs to:+ * Questions no longer go through the entity framework β CRUD lives in+ * `metabase/api/card`. The slice itself is still consumed by `getMetadata` in+ * `metabase/selectors/metadata.ts`, so we keep it in sync when:*- * - reflect the latest moderation status when a card is soft-reloaded, and- * - absorb ad-hoc card values injected by RTK Query consumers.+ * - a card is soft-reloaded (to reflect the latest moderation status), and+ * - an RTK Query consumer injects ad-hoc card values via+ * `INJECT_RTK_QUERY_QUESTION_VALUE`.*- * It is registered as the retired-entity reducer for `questions` in- * `metabase/redux/entities`, where it runs after `handleEntities` has merged any- * `payload.entities.questions`.+ * It runs after the generic slice reducer in `./index` has merged any+ * `payload.entities.questions` from `metabase/entities/*` actions.*/export function questionsReducer(state: QuestionState = {},diff --git a/frontend/src/metabase/entities/questions-reducer.unit.spec.ts b/frontend/src/metabase/redux/entities/questions-reducer.unit.spec.tssimilarity index 97%rename from frontend/src/metabase/entities/questions-reducer.unit.spec.tsrename to frontend/src/metabase/redux/entities/questions-reducer.unit.spec.tsindex 6ca55f7afef..eb89a121b4a 100644--- a/frontend/src/metabase/entities/questions-reducer.unit.spec.ts+++ b/frontend/src/metabase/redux/entities/questions-reducer.unit.spec.ts@@ -1,8 +1,9 @@+import { SOFT_RELOAD_CARD } from "metabase/redux/query-builder";+import {INJECT_RTK_QUERY_QUESTION_VALUE,questionsReducer,-} from "metabase/entities/questions-reducer";-import { SOFT_RELOAD_CARD } from "metabase/redux/query-builder";+} from "./questions-reducer";describe("questionsReducer", () => {describe(SOFT_RELOAD_CARD, () => {diff --git a/frontend/src/metabase/entities/tables-reducer.ts b/frontend/src/metabase/redux/entities/tables-reducer.tssimilarity index 88%rename from frontend/src/metabase/entities/tables-reducer.tsrename to frontend/src/metabase/redux/entities/tables-reducer.tsindex 2b64eef641d..e4d80c2675c 100644--- a/frontend/src/metabase/entities/tables-reducer.ts+++ b/frontend/src/metabase/redux/entities/tables-reducer.ts@@ -14,16 +14,16 @@ type ReducerAction = { type: string; payload?: any; error?: unknown };/*** Reducer for the `state.entities.tables` slice.*- * The `tables` entity has been removed from the entity framework (its CRUD now- * lives in `metabase/api/table`), but the normalized slice still needs to:+ * Tables no longer go through the entity framework β CRUD lives in+ * `metabase/api/table`. The slice itself is still consumed by `getMetadata` in+ * `metabase/selectors/metadata.ts`, so we keep it in sync when:*- * - keep virtual tables (the `card__<id>` representation of saved questions) in- * sync as questions are created, updated, and archived, and- * - keep `original_fields` in sync when a field is updated elsewhere.+ * - questions are created/updated/archived (the saved-question virtual table+ * `card__<id>` representation needs to track them), and+ * - a field is updated elsewhere (so `original_fields` doesn't go stale).*- * It is registered as the retired-entity reducer for `tables` in- * `metabase/redux/entities`, where it runs after `handleEntities` has merged any- * `payload.entities.tables`.+ * It runs after the generic slice reducer in `./index` has merged any+ * `payload.entities.tables` from `metabase/entities/*` actions.*/export function tablesReducer(state: TableState = {},diff --git a/frontend/src/metabase/entities/tables-reducer.unit.spec.ts b/frontend/src/metabase/redux/entities/tables-reducer.unit.spec.tssimilarity index 99%rename from frontend/src/metabase/entities/tables-reducer.unit.spec.tsrename to frontend/src/metabase/redux/entities/tables-reducer.unit.spec.tsindex f6ec2423fd4..8dfc544b0d5 100644--- a/frontend/src/metabase/entities/tables-reducer.unit.spec.ts+++ b/frontend/src/metabase/redux/entities/tables-reducer.unit.spec.ts@@ -1,8 +1,9 @@-import { tablesReducer } from "metabase/entities/tables-reducer";import { cardCreated, cardUpdated } from "metabase/redux/cards";import { convertSavedQuestionToVirtualTable } from "metabase-lib/v1/metadata/utils/saved-questions";import type { Card } from "metabase-types/api";+import { tablesReducer } from "./tables-reducer";+describe("tablesReducer", () => {describe("saved questions virtual table sync", () => {function getQuestion({diff --git a/frontend/src/metabase/redux/metadata-typed.ts b/frontend/src/metabase/redux/metadata-typed.tsindex a36416f511a..b7c7684b8c8 100644--- a/frontend/src/metabase/redux/metadata-typed.ts+++ b/frontend/src/metabase/redux/metadata-typed.ts@@ -1,7 +1,8 @@import { type Schema, normalize } from "normalizr";-// this action is handled by entity reducers in `handleEntities` in-// `frontend/src/metabase/entities/utils.js`+// Handled by the per-slice reducers in `metabase/redux/entities` β see+// `makeSliceReducer` there, which merges `payload.entities.<name>` into the+// matching `state.entities.<name>` slice so `getMetadata` picks up the change.const UPDATE = "metabase/entities/UPDATE";export function updateMetadata(data: unknown, schema: Schema) {diff --git a/frontend/src/metabase/redux/metadata.js b/frontend/src/metabase/redux/metadata.jsindex ccee4285e44..2aa534ee2c5 100644--- a/frontend/src/metabase/redux/metadata.js+++ b/frontend/src/metabase/redux/metadata.js@@ -10,7 +10,7 @@ import {segmentApi,tableApi,} from "metabase/api";-import { entityCompatibleQuery } from "metabase/entities/utils";+import { runRtkEndpoint } from "metabase/api/utils/run-rtk-endpoint";import { isProduction } from "metabase/env";import { createThunkAction } from "metabase/redux";import { fetchTableMetadataAndForeignKeys } from "metabase/redux/tables";@@ -33,27 +33,19 @@ const deprecated = (message) => {export const fetchSegments = () => (dispatch) => {deprecated("metabase/redux/metadata fetchSegments");- return entityCompatibleQuery(- undefined,- dispatch,- segmentApi.endpoints.listSegments,- );+ return runRtkEndpoint(undefined, dispatch, segmentApi.endpoints.listSegments);};export const updateSegment = (segment) => (dispatch) => {deprecated("metabase/redux/metadata updateSegment");- return entityCompatibleQuery(- segment,- dispatch,- segmentApi.endpoints.updateSegment,- );+ return runRtkEndpoint(segment, dispatch, segmentApi.endpoints.updateSegment);};export const fetchRealDatabases =(reload = false) =>(dispatch) => {deprecated("metabase/redux/metadata fetchRealDatabases");- return entityCompatibleQuery(+ return runRtkEndpoint({ include: "tables" },dispatch,databaseApi.endpoints.listDatabases,@@ -65,7 +57,7 @@ export const fetchDatabaseMetadata =(dbId, reload = false) =>(dispatch) => {deprecated("metabase/redux/metadata fetchDatabaseMetadata");- return entityCompatibleQuery(+ return runRtkEndpoint({ id: dbId },dispatch,databaseApi.endpoints.getDatabaseMetadata,@@ -76,7 +68,7 @@ export const fetchDatabaseMetadata =export const updateDatabase = (database) => async (dispatch) => {deprecated("metabase/redux/metadata updateDatabase");const slimDatabase = _.omit(database, "tables", "tables_lookup");- const result = await entityCompatibleQuery(+ const result = await runRtkEndpoint(slimDatabase,dispatch,databaseApi.endpoints.updateDatabase,@@ -94,7 +86,7 @@ export const updateTable = (table) => async (dispatch) => {"aggregation_operators","segments",);- const result = await entityCompatibleQuery(+ const result = await runRtkEndpoint(slimTable,dispatch,tableApi.endpoints.updateTable,@@ -110,7 +102,7 @@ export const fetchTableMetadata = (id, reload = false) => {export const updateFieldValues = (fieldId, fieldValuePairs) => (dispatch) => {deprecated("metabase/redux/metadata updateFieldValues");- return entityCompatibleQuery(+ return runRtkEndpoint({ id: fieldId, values: fieldValuePairs },dispatch,fieldApi.endpoints.updateFieldValues,@@ -120,7 +112,7 @@ export const updateFieldValues = (fieldId, fieldValuePairs) => (dispatch) => {export const updateField = (field) => async (dispatch) => {deprecated("metabase/redux/metadata updateField");const slimField = _.omit(field, "filter_operators_lookup");- const result = await entityCompatibleQuery(+ const result = await runRtkEndpoint(slimField,dispatch,fieldApi.endpoints.updateField,@@ -131,7 +123,7 @@ export const updateField = (field) => async (dispatch) => {export const deleteFieldDimension = (fieldId) => async (dispatch) => {deprecated("metabase/redux/metadata deleteFieldDimension");- const result = await entityCompatibleQuery(+ const result = await runRtkEndpoint(fieldId,dispatch,fieldApi.endpoints.deleteFieldDimension,@@ -143,7 +135,7 @@ export const deleteFieldDimension = (fieldId) => async (dispatch) => {export const updateFieldDimension =(fieldId, dimension) => async (dispatch) => {deprecated("metabase/redux/metadata updateFieldDimension");- const result = await entityCompatibleQuery(+ const result = await runRtkEndpoint({ id: fieldId, ...dimension },dispatch,fieldApi.endpoints.createFieldDimension,@@ -239,7 +231,7 @@ export const fetchRemapping = createThunkAction(const entityIdentifier = uuid ?? token ?? null;let remapping;if (dashboardId != null) {- remapping = await entityCompatibleQuery(+ remapping = await runRtkEndpoint({...(entityIdentifier? { entityIdentifier }@@ -252,7 +244,7 @@ export const fetchRemapping = createThunkAction({ forceRefetch: false },);} else if (cardId != null) {- remapping = await entityCompatibleQuery(+ remapping = await runRtkEndpoint({...(entityIdentifier ? { entityIdentifier } : { card_id: cardId }),parameter_id: parameter.id,@@ -265,7 +257,7 @@ export const fetchRemapping = createThunkAction(} else if (field != null) {// Field-based remapping (e.g. FK display fields). Static-list sources// carry their [value, label] pairs inline and need no network call.- remapping = await entityCompatibleQuery(+ remapping = await runRtkEndpoint({parameter: normalizeParameter(parameter),field_ids: [field.id],diff --git a/frontend/src/metabase/redux/requests.ts b/frontend/src/metabase/redux/requests.tsindex 6d40fb12801..40acff92894 100644--- a/frontend/src/metabase/redux/requests.ts+++ b/frontend/src/metabase/redux/requests.ts@@ -186,7 +186,7 @@ const isBulkInvalidation = (statePath: (string | number)[]): boolean => {};export const requestsReducer = (- state: RequestsStateTree,+ state: RequestsStateTree = {},action: RequestsAction,): RequestsStateTree => {if (action?.payload?.statePath) {diff --git a/frontend/src/metabase/redux/store/entities.ts b/frontend/src/metabase/redux/store/entities.tsindex da26c2a85bf..3a7417f4572 100644--- a/frontend/src/metabase/redux/store/entities.ts+++ b/frontend/src/metabase/redux/store/entities.ts@@ -12,6 +12,19 @@ import type {NormalizedTable,} from "metabase-types/api";+// backend returns model = "card" instead of "question"+export const entityTypeForModel = (model: string): string => {+ if (model === "card" || model === "dataset" || model === "metric") {+ return "questions";+ }+ return `${model}s`;+};++export const entityTypeForObject = (+ object?: { model: string } | null,+): string | undefined =>+ object ? entityTypeForModel(object.model) : undefined;+export interface EntitiesState {collections: Record<string, NormalizedCollection>;dashboards: Record<string, NormalizedDashboard>;@@ -24,6 +37,4 @@ export interface EntitiesState {metrics: Record<string, NormalizedMetric>;snippets: Record<string, NormalizedNativeQuerySnippet>;questions: Record<string, NormalizedCard>;-- [key: `${string}_list`]: unknown;}diff --git a/frontend/src/metabase/redux/store/entities.unit.spec.ts b/frontend/src/metabase/redux/store/entities.unit.spec.tsnew file mode 100644index 00000000000..3c08b0d2fb2--- /dev/null+++ b/frontend/src/metabase/redux/store/entities.unit.spec.ts@@ -0,0 +1,33 @@+import { entityTypeForModel, entityTypeForObject } from "./entities";++const MODEL_ENTITY_TYPE = [+ { model: "card", entityType: "questions" },+ { model: "dataset", entityType: "questions" },+ { model: "dashboard", entityType: "dashboards" },+ { model: "pulse", entityType: "pulses" },+ { model: "collection", entityType: "collections" },+ { model: "segment", entityType: "segments" },+ { model: "metric", entityType: "questions" },+ { model: "snippet", entityType: "snippets" },+ { model: "snippetCollection", entityType: "snippetCollections" },+];++describe("entityTypeForModel", () => {+ MODEL_ENTITY_TYPE.forEach(({ model, entityType }) => {+ it(`returns "${entityType}" for "${model}" model`, () => {+ expect(entityTypeForModel(model)).toBe(entityType);+ });+ });+});++describe("entityTypeForObject", () => {+ MODEL_ENTITY_TYPE.forEach(({ model, entityType }) => {+ it(`returns "${entityType}" for "${model}" model`, () => {+ expect(entityTypeForObject({ model })).toBe(entityType);+ });+ });++ it("handles undefined object", () => {+ expect(entityTypeForObject()).toBe(undefined);+ });+});diff --git a/frontend/src/metabase/redux/tables.ts b/frontend/src/metabase/redux/tables.tsindex 4b2802af1c9..066aee3a144 100644--- a/frontend/src/metabase/redux/tables.ts+++ b/frontend/src/metabase/redux/tables.ts@@ -1,5 +1,5 @@import { fieldApi, tableApi } from "metabase/api";-import { entityCompatibleQuery } from "metabase/entities/utils";+import { runRtkEndpoint } from "metabase/api/utils/run-rtk-endpoint";import { updateMetadata } from "metabase/redux/metadata-typed";import type { Dispatch, GetState } from "metabase/redux/store";import { TableSchema } from "metabase/schema";@@ -37,7 +37,7 @@ export const fetchTableMetadata =options: FetchOptions = {},) =>async (dispatch: Dispatch) =>- entityCompatibleQuery(+ runRtkEndpoint({ id, ...params, ...options.params },dispatch,tableApi.endpoints.getTableQueryMetadata,@@ -58,7 +58,7 @@ export const fetchTableForeignKeys =if (table?.fks != null) {return { id, fks: table.fks };}- const fks = await entityCompatibleQuery(+ const fks = await runRtkEndpoint(id,dispatch,tableApi.endpoints.listTableForeignKeys,@@ -86,12 +86,9 @@ export const fetchTableMetadataAndForeignKeys =// overridden model FK columns have fk_target_field_id but don't have a// target β in this case we load the field instead of the table...getTableForeignKeyFieldIds(table).map((fieldId) =>- entityCompatibleQuery(- { id: fieldId },- dispatch,- fieldApi.endpoints.getField,- { forceRefetch: options.reload ?? false },- ),+ runRtkEndpoint({ id: fieldId }, dispatch, fieldApi.endpoints.getField, {+ forceRefetch: options.reload ?? false,+ }),),]);};diff --git a/frontend/src/metabase/redux/uploads.ts b/frontend/src/metabase/redux/uploads.tsindex ebd4b2cf532..b4c514b8c81 100644--- a/frontend/src/metabase/redux/uploads.ts+++ b/frontend/src/metabase/redux/uploads.ts@@ -3,7 +3,7 @@ import { t } from "ttag";import { Api, cardApi, tableApi } from "metabase/api";import { listTag } from "metabase/api/tags";-import { entityCompatibleQuery } from "metabase/entities/utils";+import { runRtkEndpoint } from "metabase/api/utils/run-rtk-endpoint";import type { Dispatch, State } from "metabase/redux/store";import type { FileUploadState } from "metabase/redux/store/upload";import { UploadMode } from "metabase/redux/store/upload";@@ -97,20 +97,20 @@ export const uploadFile = createThunkAction(const response = await (() => {switch (uploadMode) {case UploadMode.append:- return entityCompatibleQuery(+ return runRtkEndpoint({ tableId, formData },dispatch,tableApi.endpoints.appendTableCsv,);case UploadMode.replace:- return entityCompatibleQuery(+ return runRtkEndpoint({ tableId, formData },dispatch,tableApi.endpoints.replaceTableCsv,);case UploadMode.create:default:- return entityCompatibleQuery(+ return runRtkEndpoint({ file, collection_id: collectionId },dispatch,cardApi.endpoints.createCardFromCsv,diff --git a/frontend/src/metabase/reference/databases/TableQuestionsContainer.tsx b/frontend/src/metabase/reference/databases/TableQuestionsContainer.tsxindex 2f17f75f59e..5c211b90466 100644--- a/frontend/src/metabase/reference/databases/TableQuestionsContainer.tsx+++ b/frontend/src/metabase/reference/databases/TableQuestionsContainer.tsx@@ -3,9 +3,9 @@ import type { Location } from "history";import { Component } from "react";import { cardApi } from "metabase/api";+import { runRtkEndpoint } from "metabase/api/utils/run-rtk-endpoint";import { SidebarLayout } from "metabase/common/components/SidebarLayout";import CS from "metabase/css/core/index.css";-import { entityCompatibleQuery } from "metabase/entities/utils";import { connect } from "metabase/redux";import * as metadataActions from "metabase/redux/metadata";import type { Dispatch } from "metabase/redux/store";@@ -40,7 +40,7 @@ const mapStateToProps = (const mapDispatchToProps = {fetchQuestions: () => (dispatch: Dispatch) =>- entityCompatibleQuery({}, dispatch, cardApi.endpoints.listCards),+ runRtkEndpoint({}, dispatch, cardApi.endpoints.listCards),...metadataActions,...actions,};diff --git a/frontend/src/metabase/reference/segments/SegmentQuestionsContainer.tsx b/frontend/src/metabase/reference/segments/SegmentQuestionsContainer.tsxindex 73565030c87..97a228d5f95 100644--- a/frontend/src/metabase/reference/segments/SegmentQuestionsContainer.tsx+++ b/frontend/src/metabase/reference/segments/SegmentQuestionsContainer.tsx@@ -3,9 +3,9 @@ import type { Location } from "history";import { Component } from "react";import { cardApi } from "metabase/api";+import { runRtkEndpoint } from "metabase/api/utils/run-rtk-endpoint";import { SidebarLayout } from "metabase/common/components/SidebarLayout";import CS from "metabase/css/core/index.css";-import { entityCompatibleQuery } from "metabase/entities/utils";import { connect } from "metabase/redux";import * as metadataActions from "metabase/redux/metadata";import type { Dispatch } from "metabase/redux/store";@@ -36,7 +36,7 @@ const mapStateToProps = (const mapDispatchToProps = {fetchQuestions: () => (dispatch: Dispatch) =>- entityCompatibleQuery({}, dispatch, cardApi.endpoints.listCards),+ runRtkEndpoint({}, dispatch, cardApi.endpoints.listCards),...metadataActions,...actions,};diff --git a/frontend/src/metabase/schema.js b/frontend/src/metabase/schema.jsindex ca922135ef4..cfe182a9970 100644--- a/frontend/src/metabase/schema.js+++ b/frontend/src/metabase/schema.js@@ -2,7 +2,7 @@import { schema } from "normalizr";-import { entityTypeForObject } from "metabase/entities/utils";+import { entityTypeForObject } from "metabase/redux/store/entities";import { getUniqueFieldId } from "metabase-lib/v1/metadata/utils/fields";import { SAVED_QUESTIONS_VIRTUAL_DB_ID } from "metabase-lib/v1/metadata/utils/saved-questions";import { generateSchemaId } from "metabase-lib/v1/metadata/utils/schema";diff --git a/frontend/src/metabase/visualizations/components/ObjectDetail/ObjectDetailPanel.tsx b/frontend/src/metabase/visualizations/components/ObjectDetail/ObjectDetailPanel.tsxindex 849e680fe6e..45e7a2b3187 100644--- a/frontend/src/metabase/visualizations/components/ObjectDetail/ObjectDetailPanel.tsx+++ b/frontend/src/metabase/visualizations/components/ObjectDetail/ObjectDetailPanel.tsx@@ -5,10 +5,10 @@ import _ from "underscore";import { ActionExecuteModal } from "metabase/actions/containers/ActionExecuteModal";import { datasetApi, skipToken, useListActionsQuery } from "metabase/api";+import { runRtkEndpoint } from "metabase/api/utils/run-rtk-endpoint";import { NotFound } from "metabase/common/components/ErrorPages";import { LoadingSpinner } from "metabase/common/components/LoadingSpinner";import { useDatabaseListQuery } from "metabase/common/hooks";-import { entityCompatibleQuery } from "metabase/entities/utils";import { useDispatch } from "metabase/redux";import { ActionsApi } from "metabase/services";import { Modal } from "metabase/ui";@@ -202,11 +202,7 @@ export function ObjectDetailPanel({? Lib.toJsQuery(filterByPk(query, pkField, zoomedRowID)): undefined;- entityCompatibleQuery(- datasetQuery,- dispatch,- datasetApi.endpoints.getAdhocQuery,- )+ runRtkEndpoint(datasetQuery, dispatch, datasetApi.endpoints.getAdhocQuery).then((result) => {if (result?.data?.rows?.length > 0) {const newRow = result.data.rows[0];diff --git a/frontend/test/__support__/entities-store.ts b/frontend/test/__support__/entities-store.tsindex 18fa867acd9..c5ec93a53a9 100644--- a/frontend/test/__support__/entities-store.ts+++ b/frontend/test/__support__/entities-store.ts@@ -1,12 +1,8 @@import type { Middleware, Reducer } from "@reduxjs/toolkit";import { combineReducers, configureStore } from "@reduxjs/toolkit";-import type { Action } from "redux-actions";-import * as entities from "metabase/redux/entities";-import {- type RequestsStateTree,- requestsReducer,-} from "metabase/redux/requests";+import { reducer as entitiesReducer } from "metabase/redux/entities";+import { requestsReducer } from "metabase/redux/requests";import type { State } from "metabase/redux/store";/**@@ -21,11 +17,8 @@ export function getStore(middleware: Middleware[] = [],) {const reducer = combineReducers({- entities: entities.reducer,- requests: (- state: RequestsStateTree | undefined,- action: Action<undefined>,- ) => requestsReducer(entities.requestsReducer(state, action), action),+ entities: entitiesReducer,+ requests: requestsReducer,...reducers,}) as unknown as Reducer<State>;