nomadro/lib/use-remote-config.ts
eric 9f8fec1723 Ship portal PC/H5 acceptance, VIP ScrollReader, admin analytics and ops anchors.
Adds /api/health, ntfy notify on config save, /admin/analytics charts, and deploy smoke for miniprogram config/API.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-28 23:52:00 -05:00

92 lines
2.1 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"use client";
import { useEffect, useState } from "react";
import {
DEFAULT_REMOTE_CONFIG,
mergeRemoteConfig,
type NomadroRemoteConfig,
} from "~/lib/remote-config";
const CACHE_KEY = "nomadro_web_remote_config_v1";
type Result = {
config: NomadroRemoteConfig;
fromOffline: boolean;
ready: boolean;
};
function readCache(): NomadroRemoteConfig | null {
try {
if (typeof window === "undefined") return null;
const raw = localStorage.getItem(CACHE_KEY);
if (!raw) return null;
const parsed = JSON.parse(raw) as { config?: Partial<NomadroRemoteConfig> };
return mergeRemoteConfig(parsed.config);
} catch {
return null;
}
}
function writeCache(config: NomadroRemoteConfig) {
try {
localStorage.setItem(
CACHE_KEY,
JSON.stringify({ ts: Date.now(), config }),
);
} catch {
/* ignore */
}
}
function initialState(): Result {
// SSR / 首屏:包内默认即 ready,避免整页挡「加载配置」
return {
config: DEFAULT_REMOTE_CONFIG,
fromOffline: true,
ready: true,
};
}
/** 门户远程配置:首屏默认可开 → 网络刷新 → localStorage 兜底 */
export function useRemoteConfig(): Result {
const [state, setState] = useState<Result>(initialState);
useEffect(() => {
let cancelled = false;
const cached = readCache();
if (cached) {
setState({ config: cached, fromOffline: true, ready: true });
}
(async () => {
try {
const res = await fetch("/api/config", { cache: "no-store" });
const data = await res.json().catch(() => ({}));
if (cancelled) return;
if (res.ok && data?.config) {
const config = mergeRemoteConfig(data.config);
writeCache(config);
setState({ config, fromOffline: false, ready: true });
return;
}
} catch {
/* fallthrough */
}
if (cancelled) return;
if (!cached) {
setState({
config: DEFAULT_REMOTE_CONFIG,
fromOffline: true,
ready: true,
});
}
})();
return () => {
cancelled = true;
};
}, []);
return state;
}