Skip to content

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

Move endpoints from `CardApi` out of `services.js` (#74076)

Romeo Van Snick999ed32c6cab
diff --git a/frontend/src/embedding-sdk-bundle/lib/load-static-question.ts b/frontend/src/embedding-sdk-bundle/lib/load-static-question.ts
deleted file mode 100644
index 2ece3e2aa53..00000000000
--- a/frontend/src/embedding-sdk-bundle/lib/load-static-question.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-import { CardApi } from "metabase/services";
-import type { Deferred } from "metabase/utils/promise";
-import type { Card, Dataset, ParameterQueryObject } from "metabase-types/api";
-
-interface Options {
- questionId: number;
- sqlParameters?: Record<string, string | number>;
- cancelDeferred?: Deferred;
-}
-
-type ParameterQueryInput = { id: string } & ParameterQueryObject;
-
-export async function loadStaticQuestion(options: Options) {
- const { questionId, sqlParameters, cancelDeferred } = options;
-
- let card: Card | null;
- let result: Dataset | null;
-
- const cancelled = cancelDeferred?.promise;
-
- [card, result] = await Promise.all([
- CardApi.get({ cardId: questionId }, { cancelled }),
-
- // Query the card in parallel when no parameters are provided.
- !sqlParameters && CardApi.query({ cardId: questionId }, { cancelled }),
- ]);
-
- if (sqlParameters && card?.parameters) {
- const parameters: ParameterQueryInput[] = card.parameters
- .filter((parameter) => parameter.target)
- .map((parameter) => ({
- id: parameter.id,
- type: parameter.type,
- target: parameter.target!,
- value: sqlParameters[parameter.slug],
- }));
-
- result = await CardApi.query(
- { cardId: questionId, parameters },
- { cancelled },
- );
- }
-
- return { card, result };
-}
diff --git a/frontend/src/metabase/api/card.ts b/frontend/src/metabase/api/card.ts
index e578fa0b67f..d853b123594 100644
--- a/frontend/src/metabase/api/card.ts
+++ b/frontend/src/metabase/api/card.ts
@@ -16,9 +16,12 @@ import type {
GetPublicCard,
GetRemappedCardParameterValueRequest,
ListCardsRequest,
+ ParameterId,
+ ParameterValues,
UpdateCardKeyRequest,
UpdateCardRequest,
} from "metabase-types/api";
+import type { EntityToken, EntityUuid } from "metabase-types/api/entity";
import { Api } from "./api";
import {
@@ -36,6 +39,16 @@ import { handleQueryFulfilled } from "./utils/lifecycle";
const PERSISTED_MODEL_REFRESH_DELAY = 200;
+export type CardParameterValuesRequest = {
+ cardId?: CardId | EntityToken;
+ entityIdentifier?: EntityUuid | EntityToken | null;
+ paramId: ParameterId;
+};
+
+export type SearchCardParameterValuesRequest = CardParameterValuesRequest & {
+ query: string;
+};
+
export const cardApi = Api.injectEndpoints({
endpoints: (builder) => {
const updateCardPropertiesMutation = <
@@ -96,6 +109,39 @@ export const cardApi = Api.injectEndpoints({
providesTags: (_data, _error, { cardId }) =>
provideCardQueryTags(cardId),
}),
+ getCardQueryPivot: builder.query<Dataset, CardQueryRequest>({
+ query: ({ cardId, ...body }) => ({
+ method: "POST",
+ url: `/api/card/pivot/${cardId}/query`,
+ body,
+ }),
+ providesTags: (_data, _error, { cardId }) =>
+ provideCardQueryTags(cardId),
+ }),
+ getCardParameterValues: builder.query<
+ ParameterValues,
+ CardParameterValuesRequest
+ >({
+ query: (params) => ({
+ method: "GET",
+ url: "/api/card/:cardId/params/:paramId/values",
+ params,
+ }),
+ providesTags: (_response, _error, { paramId }) =>
+ provideParameterValuesTags(paramId),
+ }),
+ searchCardParameterValues: builder.query<
+ ParameterValues,
+ SearchCardParameterValuesRequest
+ >({
+ query: (params) => ({
+ method: "GET",
+ url: "/api/card/:cardId/params/:paramId/search/:query",
+ params,
+ }),
+ providesTags: (_response, _error, { paramId }) =>
+ provideParameterValuesTags(paramId),
+ }),
getRemappedCardParameterValue: builder.query<
FieldValue,
GetRemappedCardParameterValueRequest
@@ -327,6 +373,10 @@ export const {
useGetCardQueryMetadataQuery,
useGetCardQueryQuery,
useLazyGetCardQueryQuery,
+ useGetCardQueryPivotQuery,
+ useLazyGetCardQueryPivotQuery,
+ useGetCardParameterValuesQuery,
+ useSearchCardParameterValuesQuery,
useGetRemappedCardParameterValueQuery,
useCreateCardMutation,
useUpdateCardMutation,
diff --git a/frontend/src/metabase/common/components/ErrorPages/use-error-info.ts b/frontend/src/metabase/common/components/ErrorPages/use-error-info.ts
index b75b7a5872c..4b3891959de 100644
--- a/frontend/src/metabase/common/components/ErrorPages/use-error-info.ts
+++ b/frontend/src/metabase/common/components/ErrorPages/use-error-info.ts
@@ -3,7 +3,7 @@ import { t } from "ttag";
import { useLazyGetBugReportDetailsQuery } from "metabase/api/bug-report";
import { useLazyListLogsQuery } from "metabase/api/logger";
-import { useSelector } from "metabase/redux";
+import { useDispatch, useSelector } from "metabase/redux";
import { getUser, getUserIsAdmin } from "metabase/selectors/user";
import { MetabaseApi } from "metabase/services";
@@ -27,6 +27,7 @@ export const useErrorInfo = (
) => {
const currentUser = useSelector(getUser);
const isAdmin = useSelector(getUserIsAdmin);
+ const dispatch = useDispatch();
const location = window.location.href;
const [getBugReportDetails] = useLazyGetBugReportDetailsQuery();
const [listLogs] = useLazyListLogsQuery();
@@ -47,7 +48,12 @@ export const useErrorInfo = (
const isAdHoc = entity === "question" && window.location.href.includes("#");
- const entityInfoRequest = getEntityDetails({ entity, id, isAdHoc });
+ const entityInfoRequest = getEntityDetails({
+ entity,
+ id,
+ isAdHoc,
+ dispatch,
+ });
const bugReportDetailsRequest = isAdmin
? getBugReportDetails().unwrap().catch(nullOnCatch)
: Promise.resolve(null);
@@ -82,6 +88,7 @@ export const useErrorInfo = (
entityInfo.originalCard = await getEntityDetails({
entity,
id: entityInfo.original_card_id,
+ dispatch,
});
}
diff --git a/frontend/src/metabase/common/components/ErrorPages/utils.ts b/frontend/src/metabase/common/components/ErrorPages/utils.ts
index bac2510660f..6f6d5a0c95e 100644
--- a/frontend/src/metabase/common/components/ErrorPages/utils.ts
+++ b/frontend/src/metabase/common/components/ErrorPages/utils.ts
@@ -1,6 +1,8 @@
import Bowser from "bowser";
-import { CardApi, CollectionsApi, DashboardApi } from "metabase/services";
+import { cardApi } from "metabase/api";
+import type { DispatchFn } from "metabase/redux";
+import { CollectionsApi, DashboardApi } from "metabase/services";
import { b64url_to_utf8 } from "metabase/utils/encoding";
import type { ReportableEntityName } from "./types";
@@ -9,10 +11,12 @@ export const getEntityDetails = ({
entity,
id,
isAdHoc,
+ dispatch,
}: {
entity?: ReportableEntityName;
id?: string;
isAdHoc?: boolean;
+ dispatch: DispatchFn;
}) => {
if (!id || !entity) {
return Promise.resolve(null);
@@ -30,7 +34,9 @@ export const getEntityDetails = ({
return Promise.resolve("unable to decode ad-hoc question");
}
}
- return CardApi.get({ cardId: id }).catch(nullOnCatch);
+ return dispatch(cardApi.endpoints.getCard.initiate({ id }))
+ .unwrap()
+ .catch(nullOnCatch);
case "dashboard":
return DashboardApi.get({ id }).catch(nullOnCatch);
case "collection":
diff --git a/frontend/src/metabase/dashboard/actions/cards.unit.spec.ts b/frontend/src/metabase/dashboard/actions/cards.unit.spec.ts
index 47e9d82f3fb..4e38aff40d5 100644
--- a/frontend/src/metabase/dashboard/actions/cards.unit.spec.ts
+++ b/frontend/src/metabase/dashboard/actions/cards.unit.spec.ts
@@ -1,4 +1,5 @@
import type { Store } from "@reduxjs/toolkit";
+import fetchMock from "fetch-mock";
import _ from "underscore";
import { getStore } from "__support__/entities-store";
@@ -15,7 +16,6 @@ import {
createMockDashboardState,
createMockState,
} from "metabase/redux/store/mocks";
-import { CardApi } from "metabase/services";
import type {
CardId,
DashCardId,
@@ -259,17 +259,17 @@ describe("dashboard/actions/cards", () => {
});
it("should run a new card query", async () => {
- const { cardQueryEndpointSpy } = await runReplaceCardAction({
+ await runReplaceCardAction({
dashcardId: TABLE_DASHCARD.id,
nextCardId: ORDERS_LINE_CHART_CARD.id,
});
// It's important to ensure the `/card/:id/query` endpoint is called
// Regular dashcard query endpoint won't work with a new `card_id`
- expect(cardQueryEndpointSpy).toHaveBeenCalledWith(
- { cardId: ORDERS_LINE_CHART_CARD.id },
- expect.anything(), // abort signal
+ const queryCalls = fetchMock.callHistory.calls(
+ `path:/api/card/${ORDERS_LINE_CHART_CARD.id}/query`,
);
+ expect(queryCalls).toHaveLength(1);
});
it("should not auto-wire parameters", async () => {
@@ -338,7 +338,6 @@ async function runReplaceCardAction({
const { store } = setup(opts);
const dispatchSpy = jest.spyOn(store, "dispatch");
- const cardQueryEndpointSpy = jest.spyOn(CardApi, "query");
await replaceCard({ dashcardId, nextCardId })(store.dispatch, store.getState);
const nextState = store.getState();
@@ -346,7 +345,6 @@ async function runReplaceCardAction({
return {
nextDashCard: getDashCardById(nextState, dashcardId),
dispatchSpy,
- cardQueryEndpointSpy,
};
}
diff --git a/frontend/src/metabase/dashboard/actions/data-fetching.ts b/frontend/src/metabase/dashboard/actions/data-fetching.ts
index 9d7acaffa03..bdeb581536a 100644
--- a/frontend/src/metabase/dashboard/actions/data-fetching.ts
+++ b/frontend/src/metabase/dashboard/actions/data-fetching.ts
@@ -4,7 +4,7 @@ import { denormalize, normalize, schema } from "normalizr";
import { t } from "ttag";
import _ from "underscore";
-import { automagicDashboardsApi, dashboardApi } from "metabase/api";
+import { automagicDashboardsApi, cardApi, dashboardApi } from "metabase/api";
import { applyParameters } from "metabase/common/utils/card";
import { showAutoApplyFiltersToast } from "metabase/dashboard/actions/parameters";
import { DASHBOARD_SLOW_TIMEOUT } from "metabase/dashboard/constants";
@@ -33,12 +33,12 @@ import { createAsyncThunk, createThunkAction } from "metabase/redux/utils";
import { getMetadata } from "metabase/selectors/metadata";
import {
AutoApi,
- CardApi,
DashboardApi,
EmbedApi,
MetabaseApi,
PublicApi,
maybeUsePivotEndpoint,
+ shouldUsePivotEndpoint,
} from "metabase/services";
import {
getDashboardType,
@@ -402,28 +402,42 @@ export const fetchCardDataAction = createAsyncThunk<
hasReplacedCard;
// new dashcards and new additional series cards aren't yet saved to the dashboard, so they need to be run using the card query endpoint
- const endpoint = shouldUseCardQueryEndpoint
- ? CardApi.query
- : DashboardApi.cardQuery;
-
- const requestBody = shouldUseCardQueryEndpoint
- ? { cardId: card.id, ignore_cache: ignoreCache }
- : {
- dashboardId: dashcard.dashboard_id,
- dashcardId: dashcard.id,
- cardId: card.id,
- parameters: datasetQuery.parameters,
- ignore_cache: ignoreCache,
- dashboard_id: dashcard.dashboard_id,
- dashboard_load_id: dashboardLoadId,
- };
- result = (await fetchDataOrError(
- maybeUsePivotEndpoint(
- endpoint,
- card,
- metadata,
- )(requestBody, queryOptions),
- )) as Dataset | { error: unknown };
+ if (shouldUseCardQueryEndpoint) {
+ const cardQueryEndpoint = shouldUsePivotEndpoint(card, metadata)
+ ? cardApi.endpoints.getCardQueryPivot
+ : cardApi.endpoints.getCardQuery;
+ const queryAction = dispatch(
+ cardQueryEndpoint.initiate(
+ { cardId: card.id, ignore_cache: ignoreCache },
+ { forceRefetch: true },
+ ),
+ );
+ deferred.promise.then(() => queryAction.abort());
+ try {
+ result = (await fetchDataOrError(queryAction.unwrap())) as
+ | Dataset
+ | { error: unknown };
+ } finally {
+ queryAction.unsubscribe?.();
+ }
+ } else {
+ const requestBody = {
+ dashboardId: dashcard.dashboard_id,
+ dashcardId: dashcard.id,
+ cardId: card.id,
+ parameters: datasetQuery.parameters,
+ ignore_cache: ignoreCache,
+ dashboard_id: dashcard.dashboard_id,
+ dashboard_load_id: dashboardLoadId,
+ };
+ result = (await fetchDataOrError(
+ maybeUsePivotEndpoint(
+ DashboardApi.cardQuery,
+ card,
+ metadata,
+ )(requestBody, queryOptions),
+ )) as Dataset | { error: unknown };
+ }
}
// If the request was not previously cancelled, then clear the defer for the card
diff --git a/frontend/src/metabase/dashboard/actions/save.ts b/frontend/src/metabase/dashboard/actions/save.ts
index eeba7e20933..b86c08815dc 100644
--- a/frontend/src/metabase/dashboard/actions/save.ts
+++ b/frontend/src/metabase/dashboard/actions/save.ts
@@ -1,18 +1,17 @@
import { assocIn, dissocIn, getIn } from "icepick";
import _ from "underscore";
+import { cardApi } from "metabase/api";
import { Dashboards } from "metabase/entities/dashboards";
import { clickBehaviorIsValid } from "metabase/parameters/utils/click-behavior";
import { createThunkAction } from "metabase/redux";
import { UPDATE_DASHBOARD_AND_CARDS } from "metabase/redux/dashboard";
+import type { StoreDashboard, StoreDashcard } from "metabase/redux/store";
import type {
- Dispatch,
- GetState,
- StoreDashboard,
- StoreDashcard,
-} from "metabase/redux/store";
-import { CardApi } from "metabase/services";
-import type { DashCardId, ParameterId } from "metabase-types/api";
+ DashCardId,
+ ParameterId,
+ UpdateCardRequest,
+} from "metabase-types/api";
import { trackDashboardSaved } from "../analytics";
import { getDashboardBeforeEditing } from "../selectors";
@@ -31,7 +30,7 @@ export const UPDATE_DASHBOARD = "metabase/dashboard/UPDATE_DASHBOARD";
export const updateDashboardAndCards = createThunkAction(
UPDATE_DASHBOARD_AND_CARDS,
function () {
- return async function (dispatch: Dispatch, getState: GetState) {
+ return async function (dispatch, getState) {
const startTime = performance.now();
const state = getState();
const { dashboards, dashcards, dashboardId } = state.dashboard;
@@ -152,7 +151,13 @@ export const updateDashboardAndCards = createThunkAction(
await Promise.all(
dashboard.dashcards
.filter((dc) => "isDirty" in dc.card && Boolean(dc.card.isDirty))
- .map(async (dc) => CardApi.update(dc.card)),
+ .map((dc) =>
+ dispatch(
+ cardApi.endpoints.updateCard.initiate(
+ dc.card as UpdateCardRequest,
+ ),
+ ).unwrap(),
+ ),
);
trackAddedIFrameDashcards(dashboard);
@@ -238,7 +243,7 @@ export const updateDashboardAndCards = createThunkAction(
export const updateDashboard = createThunkAction(
UPDATE_DASHBOARD,
function ({ attributeNames }: { attributeNames: string[] }) {
- return async function (dispatch: Dispatch, getState: GetState) {
+ return async function (dispatch, getState) {
const state = getState();
const { dashboards, dashboardId } = state.dashboard;
diff --git a/frontend/src/metabase/parameters/actions.ts b/frontend/src/metabase/parameters/actions.ts
index 4b786653d72..3288be2bbf6 100644
--- a/frontend/src/metabase/parameters/actions.ts
+++ b/frontend/src/metabase/parameters/actions.ts
@@ -1,5 +1,11 @@
-import type { Dispatch, GetState } from "metabase/redux/store";
-import { CardApi, DashboardApi, ParameterApi } from "metabase/services";
+import { cardApi } from "metabase/api";
+import type {
+ CardParameterValuesRequest,
+ SearchCardParameterValuesRequest,
+} from "metabase/api/card";
+import type { DispatchFn } from "metabase/redux";
+import type { GetState } from "metabase/redux/store";
+import { DashboardApi, ParameterApi } from "metabase/services";
import { stableStringify } from "metabase/utils/objects";
import { getNonVirtualFields } from "metabase-lib/v1/parameters/utils/parameter-fields";
import { normalizeParameter } from "metabase-lib/v1/parameters/utils/parameter-values";
@@ -31,7 +37,7 @@ export interface FetchParameterValuesPayload {
export const fetchParameterValues =
({ parameter, query }: FetchParameterValuesOpts) =>
- (dispatch: Dispatch, getState: GetState) => {
+ (dispatch: DispatchFn, getState: GetState) => {
const request = {
parameter: normalizeParameter(parameter),
field_ids: getNonVirtualFields(parameter).map((field) =>
@@ -62,12 +68,16 @@ export const fetchCardParameterValues =
parameter,
query,
}: FetchCardParameterValuesOpts) =>
- (dispatch: Dispatch, getState: GetState) => {
- const request: CardParameterValuesRequest = {
+ (dispatch: DispatchFn, getState: GetState) => {
+ const baseRequest: CardParameterValuesRequest = {
...(entityIdentifier ? { entityIdentifier } : { cardId }),
paramId: parameter.id,
- query,
};
+ const request:
+ | SearchCardParameterValuesRequest
+ | CardParameterValuesRequest = query
+ ? { ...baseRequest, query }
+ : baseRequest;
return fetchParameterValuesWithCache(
request,
@@ -93,7 +103,7 @@ export const fetchDashboardParameterValues =
parameters,
query,
}: FetchDashboardParameterValuesOpts) =>
- (dispatch: Dispatch, getState: GetState) => {
+ (dispatch: DispatchFn, getState: GetState) => {
const request: DashboardParameterValuesRequest = {
...(entityIdentifier ? { entityIdentifier } : { dashId: dashboardId }),
paramId: parameter.id,
@@ -126,22 +136,33 @@ const loadParameterValues = async (request: ParameterValuesRequest) => {
};
};
-interface CardParameterValuesRequest {
- cardId?: CardId;
- entityIdentifier?: EntityUuid | EntityToken | null;
- paramId: ParameterId;
- query?: string;
-}
-
-const loadCardParameterValues = async (request: CardParameterValuesRequest) => {
- const { values, has_more_values } = request.query
- ? await CardApi.parameterSearch(request)
- : await CardApi.parameterValues(request);
-
- return {
- values: values,
- has_more_values: request.query ? true : has_more_values,
- };
+const loadCardParameterValues = async (
+ request: CardParameterValuesRequest | SearchCardParameterValuesRequest,
+ dispatch: DispatchFn,
+) => {
+ const isSearch = "query" in request && request.query;
+ // `fetchParameterValuesWithCache` already provides caching keyed on the full
+ // request and is cleared on `API_UPDATE_QUESTION`; bypass RTK's own cache so
+ // a refetch after that reset actually hits the network.
+ const queryAction = dispatch(
+ isSearch
+ ? cardApi.endpoints.searchCardParameterValues.initiate(
+ request as SearchCardParameterValuesRequest,
+ { forceRefetch: true },
+ )
+ : cardApi.endpoints.getCardParameterValues.initiate(request, {
+ forceRefetch: true,
+ }),
+ );
+ try {
+ const { values, has_more_values } = await queryAction.unwrap();
+ return {
+ values,
+ has_more_values: isSearch ? true : has_more_values,
+ };
+ } finally {
+ queryAction.unsubscribe?.();
+ }
};
interface DashboardParameterValuesRequest {
@@ -166,15 +187,15 @@ const loadDashboardParameterValues = async (
const fetchParameterValuesWithCache = async <T>(
request: T,
- loadValues: (request: T) => Promise<ParameterValues>,
- dispatch: Dispatch,
+ loadValues: (request: T, dispatch: DispatchFn) => Promise<ParameterValues>,
+ dispatch: DispatchFn,
getState: GetState,
) => {
const requestKey = stableStringify(request);
const requestCache = getParameterValuesCache(getState());
const response = requestCache[requestKey]
? requestCache[requestKey]
- : await loadValues(request);
+ : await loadValues(request, dispatch);
const payload = { requestKey, response };
dispatch({ type: FETCH_PARAMETER_VALUES, payload });
diff --git a/frontend/src/metabase/services.js b/frontend/src/metabase/services.js
index fafe6085ba6..29e07e35b7c 100644
--- a/frontend/src/metabase/services.js
+++ b/frontend/src/metabase/services.js
@@ -69,6 +69,16 @@ async function handleQueryApiError(apiPromise) {
// To fetch that extra data we rely on specific APIs for pivot tables that mirrow the normal endpoints.
// Those endpoints take the query along with `pivot_rows` and `pivot_cols` to return the subtotal data.
// If we add breakout/grouping sets to MBQL in the future we can remove this API switching.
+export function shouldUsePivotEndpoint(card, metadata) {
+ const question = new Question(card, metadata);
+ return (
+ question.display() === "pivot" &&
+ !isNative(card) &&
+ // if we have metadata for the db, check if it supports pivots
+ (!question.database() || question.database().supportsPivots())
+ );
+}
+
export function maybeUsePivotEndpoint(api, card, metadata) {
const question = new Question(card, metadata);
@@ -91,12 +101,7 @@ export function maybeUsePivotEndpoint(api, card, metadata) {
};
}
- if (
- question.display() !== "pivot" ||
- isNative(card) ||
- // if we have metadata for the db, check if it supports pivots
- (question.database() && !question.database().supportsPivots())
- ) {
+ if (!shouldUsePivotEndpoint(card, metadata)) {
return api;
}
@@ -189,14 +194,8 @@ export async function runQuestionQuery(
}
export const CardApi = {
- get: GET("/api/card/:cardId"),
- update: PUT("/api/card/:id"),
query: POST("/api/card/:cardId/query"),
query_pivot: POST("/api/card/pivot/:cardId/query"),
- // related
- compatibleCards: GET("/api/card/:cardId/series"),
- parameterValues: GET("/api/card/:cardId/params/:paramId/values"),
- parameterSearch: GET("/api/card/:cardId/params/:paramId/search/:query"),
};
export const DashboardApi = {