Skip to content

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

Return empty body as null instead of the empty string (#74895)

Romeo Van Snick54a770c486b2
diff --git a/frontend/src/metabase/api/group-table-access-policy.ts b/frontend/src/metabase/api/group-table-access-policy.ts
index 25c593b1cdc..407ad2d7378 100644
--- a/frontend/src/metabase/api/group-table-access-policy.ts
+++ b/frontend/src/metabase/api/group-table-access-policy.ts
@@ -30,15 +30,6 @@ export const groupTableAccessPolicyApi = Api.injectEndpoints({
params,
}),
providesTags: () => [listTag("group-table-access-policy")],
- transformResponse(response: GroupTableAccessPolicy | "" | null) {
- // The api returns 204 No Content when there is no policy.
- // This gets interpreted as an empty string by RTK query, which is not what we want.
- // Here we coalesce the empty string into null.
- if (response === "") {
- return null;
- }
- return response;
- },
}),
}),
});
diff --git a/frontend/src/metabase/api/legacy-client.ts b/frontend/src/metabase/api/legacy-client.ts
index ba9a699f1b2..49f24cd1936 100644
--- a/frontend/src/metabase/api/legacy-client.ts
+++ b/frontend/src/metabase/api/legacy-client.ts
@@ -363,9 +363,13 @@ export class LegacyApi extends EventEmitter<EventMap> {
ANTI_CSRF_TOKEN = antiCsrfToken;
}
- let responseBody: Response | string | undefined = xhr.responseText;
+ // An empty body (e.g. 204 No Content) surfaces as `null`, not `""`,
+ // so callers don't have to handle "the response was empty" via
+ // per-endpoint `transformResponse` workarounds.
+ let responseBody: Response | string | null | undefined =
+ xhr.status === 204 ? null : xhr.responseText;
- if (options.json) {
+ if (options.json && xhr.responseText !== "") {
try {
responseBody = JSON.parse(xhr.responseText);
} catch (e) {}
@@ -459,9 +463,13 @@ export class LegacyApi extends EventEmitter<EventMap> {
.then((response) => {
const unreadResponse = response.clone();
return response.text().then((bodyText) => {
- let body: string | Response | undefined = bodyText;
+ // An empty body (e.g. 204 No Content) surfaces as `null`, not `""`,
+ // so callers don't have to handle "the response was empty" via
+ // per-endpoint `transformResponse` workarounds.
+ let body: string | Response | null | undefined =
+ response.status === 204 ? null : bodyText;
- if (options.json) {
+ if (options.json && bodyText !== "") {
try {
body = JSON.parse(bodyText);
} catch (e) {}
diff --git a/frontend/src/metabase/api/legacy-client.unit.spec.ts b/frontend/src/metabase/api/legacy-client.unit.spec.ts
index 054c68e9aa0..5e58396a590 100644
--- a/frontend/src/metabase/api/legacy-client.unit.spec.ts
+++ b/frontend/src/metabase/api/legacy-client.unit.spec.ts
@@ -1,3 +1,5 @@
+import fetchMock from "fetch-mock";
+
import { LegacyApi } from "./legacy-client";
type OnBeforeRequestHandlerData = {
@@ -330,4 +332,52 @@ describe("api", () => {
);
});
});
+
+ // In test environments (`isTest`) the legacy client routes every request
+ // through `_makeRequestWithFetch`, so these specs cover the fetch path. The
+ // XHR path's empty-body branch mirrors the same `status === 204` check and is
+ // exercised end-to-end by the live app; co-locating both transports' unit
+ // coverage would require a dedicated XHR mock which the spec doesn't
+ // currently set up.
+ describe("response body parsing", () => {
+ let apiInstance: LegacyApi;
+
+ beforeEach(() => {
+ apiInstance = new LegacyApi();
+ });
+
+ afterEach(() => {
+ fetchMock.removeRoutes().clearHistory();
+ });
+
+ it("resolves an empty 204 body as null (not the empty string)", async () => {
+ fetchMock.get("path:/api/empty", { status: 204, body: "" });
+
+ const result = await apiInstance.GET("/api/empty")({});
+
+ expect(result).toBeNull();
+ });
+
+ it("leaves an empty non-204 body as the empty string", async () => {
+ // Only 204 No Content is normalized to null. An empty-bodied 200 keeps
+ // its historical empty-string value so callers that index into a body
+ // (e.g. `result.id`) don't begin dereferencing null.
+ fetchMock.get("path:/api/also-empty", { status: 200, body: "" });
+
+ const result = await apiInstance.GET("/api/also-empty")({});
+
+ expect(result).toBe("");
+ });
+
+ it("parses a non-empty JSON body to its decoded value", async () => {
+ fetchMock.get("path:/api/data", {
+ status: 200,
+ body: { hello: "world" },
+ });
+
+ const result = await apiInstance.GET("/api/data")({});
+
+ expect(result).toEqual({ hello: "world" });
+ });
+ });
});
diff --git a/frontend/src/metabase/common/components/UserHasSeen/UserHasSeen.tsx b/frontend/src/metabase/common/components/UserHasSeen/UserHasSeen.tsx
index a8b23014f6a..4cd8117f687 100644
--- a/frontend/src/metabase/common/components/UserHasSeen/UserHasSeen.tsx
+++ b/frontend/src/metabase/common/components/UserHasSeen/UserHasSeen.tsx
@@ -24,7 +24,12 @@ export const UserHasSeen = ({
const indicatorContext = useContext(UserHasSeenAllContext);
const { upsertBadge, removeBadge } = indicatorContext ?? {};
- const [hasSeen, { ack, isLoading }] = useUserAcknowledgement(id, true);
+ const [acked, { ack, isLoading }] = useUserAcknowledgement(id, false);
+ // While the acknowledgement is still loading, treat the upsell as already
+ // seen so a previously-dismissed banner doesn't flash before we know its real
+ // state. Once loaded, an unset key (resolved to `null` by the API) reads as
+ // not-yet-seen so the upsell shows.
+ const hasSeen = isLoading || acked;
useEffect(() => {
const hasContext = upsertBadge && removeBadge;
diff --git a/frontend/src/metabase/common/components/upsells/components/UpsellBanner.unit.spec.tsx b/frontend/src/metabase/common/components/upsells/components/UpsellBanner.unit.spec.tsx
index fa4bb4dffa0..b2e344a036a 100644
--- a/frontend/src/metabase/common/components/upsells/components/UpsellBanner.unit.spec.tsx
+++ b/frontend/src/metabase/common/components/upsells/components/UpsellBanner.unit.spec.tsx
@@ -3,6 +3,7 @@ import { Route } from "react-router";
import {
findRequests,
+ setupNullGetUserKeyValueEndpoints,
setupUserKeyValueEndpoints,
} from "__support__/server-mocks";
import { renderWithProviders, screen, waitFor } from "__support__/ui";
@@ -136,6 +137,44 @@ describe("UpsellsBanner > Upsell Wrapper Dismissible", () => {
);
});
+ it("should show a dismissible banner when the acknowledgement key does not exist yet", async () => {
+ // A brand-new user has no acknowledgement stored, so the API responds with
+ // an empty body that resolves to `null`. The banner must still show.
+ setupNullGetUserKeyValueEndpoints();
+
+ renderWithProviders(
+ <Route
+ path="/"
+ component={() => (
+ <UpsellBanner
+ dismissible
+ campaign="fresh-campaign"
+ location="test-location"
+ title="Fresh title"
+ buttonText="Test button text"
+ buttonLink="https://test-store.metabase.com"
+ >
+ Banner content
+ </UpsellBanner>
+ )}
+ />,
+ {
+ storeInitialState: {
+ currentUser: createMockUser({ is_superuser: true }),
+ },
+ withRouter: true,
+ initialRoute: "/",
+ },
+ );
+
+ await waitFor(() => {
+ expect(screen.getByText("Fresh title")).toBeInTheDocument();
+ });
+ expect(
+ screen.getByRole("button", { name: "Dismiss banner" }),
+ ).toBeInTheDocument();
+ });
+
it("should hide component when it has been dismissed", async () => {
setup(
{
diff --git a/frontend/src/metabase/common/hooks/use-user-key-value.ts b/frontend/src/metabase/common/hooks/use-user-key-value.ts
index 53f1bdd08ac..dece9f046ba 100644
--- a/frontend/src/metabase/common/hooks/use-user-key-value.ts
+++ b/frontend/src/metabase/common/hooks/use-user-key-value.ts
@@ -63,8 +63,9 @@ export function useUserKeyValue<T extends UserKeyValue>({
const isMutating = setMutationReq.isLoading || clearMutationReq.isLoading;
const error = fetchError ?? setMutationReq.error ?? clearMutationReq.error;
- // 2025-11-10 @chodorowicz:
- // valueFromQuery for non-existing keys is "", so the default value is not returned
+ // For a non-existing key the API resolves the empty response body to `null`,
+ // so `defaultValue` is applied here. (RTK Query reports `undefined` only while
+ // the request is in flight, which also falls back to `defaultValue`.)
return {
value: user ? (valueFromQuery ?? defaultValue) : defaultValue,
setValue,
diff --git a/frontend/test/__support__/server-mocks/user-key-value.ts b/frontend/test/__support__/server-mocks/user-key-value.ts
index 9de7650db15..c2eca3ebbe0 100644
--- a/frontend/test/__support__/server-mocks/user-key-value.ts
+++ b/frontend/test/__support__/server-mocks/user-key-value.ts
@@ -56,9 +56,12 @@ export function setupGetUserKeyValueEndpoint(kv: UserKeyValue) {
}
export function setupNullGetUserKeyValueEndpoints() {
+ // A missing key has no stored value, so the backend returns 204 No Content
+ // (the `defendpoint` handler returns nil, which the response middleware maps
+ // to a 204). The client normalizes that to `null`.
return fetchMock.get(
`express:/api/user-key-value/namespace/:namespace/key/:key`,
- { status: 200 },
+ { status: 204 },
);
}