UNPKG

@softr/sdk

Version:

The SDK for building Softr apps on TanStack Start. It lets an app interact with Softr: auth, datasources, workflows and integrations.

51 lines (49 loc) • 2 kB
import { logger } from "./logger.js"; import { softrApiUrl } from "./softr-api.js"; import { fetch } from "./fetch.js"; import { readRequestCookies, serializeCookie, writeCookies } from "./cookies.js"; import { sessionConfig } from "./auth/config.js"; import { localeSettingsSchema } from "./formatting.js"; import { getRequestProtocol } from "@tanstack/react-start/server"; //#region src/locale-settings.ts const LOCALE_SETTINGS = "locale_settings"; const LOCALE_SETTINGS_TTL_SECONDS = 300; /** * The app's locale settings, or `null` when they cannot be read. Never * rejects: a failure formats with the visitor's locale and is not remembered, * so the next request tries again. */ async function readLocaleSettings() { const cache = process.env.NODE_ENV === "production"; const cached = cache ? parseLocaleSettings(readRequestCookies()[LOCALE_SETTINGS]) : null; if (cached !== null) return cached; try { const settings = await fetchLocaleSettings(); if (!cache) return settings; writeCookies([serializeCookie(LOCALE_SETTINGS, JSON.stringify(settings), { maxAge: LOCALE_SETTINGS_TTL_SECONDS, secure: getRequestProtocol() === "https" })]); return settings; } catch (error) { logger.warn("Could not read the locale settings:", error); return null; } } /** The settings in `cookie`, or `null` for anything else. The cookie is visitor input. */ function parseLocaleSettings(cookie) { if (cookie === void 0) return null; try { return localeSettingsSchema.safeParse(JSON.parse(cookie)).data ?? null; } catch { return null; } } async function fetchLocaleSettings() { const { applicationId } = sessionConfig(); const response = await fetch(`${softrApiUrl("SOFTR_PLATFORM_API_URL")}/v1/vibe/applications/${applicationId}/locale-settings`, { headers: { accept: "application/json" } }); if (!response.ok) throw new Error(`The platform answered ${response.status}`); return localeSettingsSchema.parse(await response.json()); } //#endregion export { readLocaleSettings };