Compare commits
7 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1a00f27c6a | ||
|
|
1bcbd3e37d | ||
|
|
e88770dd3f | ||
|
|
5cef15c032 | ||
|
|
970d1ac3ed | ||
|
|
0d6334592d | ||
|
|
c501bb7dd4 |
@@ -65,8 +65,8 @@
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
|
||||
<!-- Cloudflare Web Analytics -->
|
||||
<script defer src='https://static.cloudflareinsights.com/beacon.min.js' data-cf-beacon='{"token": "2aecdc025eb043bc89ce931b54a80054"}'></script>
|
||||
<!-- Cloudflare Web Analytics - Only in Production -->
|
||||
<!--CLOUDFLARE_ANALYTICS_PLACEHOLDER-->
|
||||
<!-- End Cloudflare Web Analytics -->
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "litek",
|
||||
"private": true,
|
||||
"version": "0.0.30",
|
||||
"version": "0.0.33",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
|
||||
@@ -53,7 +53,6 @@ const AVAILABLE_CURRENCIES: Currency[] = [
|
||||
const REQUIRED_CURRENCIES = ["USD", "CNY"];
|
||||
|
||||
const STORAGE_KEY = "selectedCurrencies";
|
||||
const RATES_CACHE_KEY = "currencyRatesCache";
|
||||
|
||||
const Tool: FC = () => {
|
||||
const [amounts, setAmounts] = useState<Record<string, string>>({});
|
||||
@@ -91,40 +90,13 @@ const Tool: FC = () => {
|
||||
}
|
||||
}, [selectedCurrencies]);
|
||||
|
||||
// Fetch exchange rates with date-based caching
|
||||
// Fetch exchange rates (Service Worker handles caching)
|
||||
useEffect(() => {
|
||||
const fetchRates = async () => {
|
||||
try {
|
||||
// 1. Try to load from cache
|
||||
const cached = localStorage.getItem(RATES_CACHE_KEY);
|
||||
if (cached) {
|
||||
try {
|
||||
const { rates: cachedRates, date: cachedDate } = JSON.parse(cached);
|
||||
|
||||
// Check if cached data is from today
|
||||
const today = new Date().toISOString().split('T')[0]; // YYYY-MM-DD
|
||||
|
||||
if (cachedDate === today) {
|
||||
// Cache is valid (same date), use it directly
|
||||
setRates(cachedRates);
|
||||
setLoading(false);
|
||||
return;
|
||||
} else {
|
||||
// Cache is outdated, show old data first then update in background
|
||||
setRates(cachedRates);
|
||||
setLoading(false);
|
||||
// Continue to fetch new data below
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("Failed to parse cached rates:", e);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Fetch latest data from network
|
||||
setLoading(true);
|
||||
const response = await fetch("https://api.frankfurter.app/latest?base=USD", {
|
||||
cache: "no-cache",
|
||||
});
|
||||
// Service Worker will handle caching with StaleWhileRevalidate strategy
|
||||
const response = await fetch("https://api.frankfurter.app/latest?base=USD");
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
@@ -132,36 +104,14 @@ const Tool: FC = () => {
|
||||
|
||||
const data = await response.json();
|
||||
const allRates: Record<string, number> = { USD: 1, ...data.rates };
|
||||
const apiDate = data.date; // Date from API (YYYY-MM-DD format)
|
||||
|
||||
// 3. Update state and cache
|
||||
setRates(allRates);
|
||||
localStorage.setItem(
|
||||
RATES_CACHE_KEY,
|
||||
JSON.stringify({ rates: allRates, date: apiDate })
|
||||
);
|
||||
} catch (error) {
|
||||
// If cache exists, continue using it even if network fails
|
||||
const cached = localStorage.getItem(RATES_CACHE_KEY);
|
||||
if (cached) {
|
||||
try {
|
||||
const { rates: cachedRates } = JSON.parse(cached);
|
||||
setRates(cachedRates);
|
||||
toast.info("Using cached exchange rates (network request failed)");
|
||||
} catch (e) {
|
||||
console.error("Failed to use cached rates:", e);
|
||||
console.error("Failed to fetch rates:", error);
|
||||
if (error instanceof Error) {
|
||||
toast.error(`Failed to fetch rates: ${error.message}`);
|
||||
toast.error(`Failed to fetch exchange rates: ${error.message}`);
|
||||
} else {
|
||||
toast.error("Failed to fetch rates");
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (error instanceof Error) {
|
||||
toast.error(`Failed to fetch rates: ${error.message}`);
|
||||
} else {
|
||||
toast.error("Failed to fetch rates");
|
||||
}
|
||||
toast.error("Failed to fetch exchange rates");
|
||||
}
|
||||
} finally {
|
||||
setLoading(false);
|
||||
|
||||
@@ -5,10 +5,20 @@ import tailwindcss from "@tailwindcss/vite"
|
||||
import { VitePWA } from 'vite-plugin-pwa'
|
||||
|
||||
// https://vite.dev/config/
|
||||
export default defineConfig({
|
||||
export default defineConfig(({ mode }) => ({
|
||||
plugins: [
|
||||
react(),
|
||||
tailwindcss(),
|
||||
// HTML 替换插件 - 仅在生产环境注入 Cloudflare Analytics
|
||||
{
|
||||
name: 'html-transform',
|
||||
transformIndexHtml(html) {
|
||||
const cloudflareScript = mode === 'production'
|
||||
? `<script defer src='https://static.cloudflareinsights.com/beacon.min.js' data-cf-beacon='{"token": "2aecdc025eb043bc89ce931b54a80054"}'></script>`
|
||||
: '';
|
||||
return html.replace('<!--CLOUDFLARE_ANALYTICS_PLACEHOLDER-->', cloudflareScript);
|
||||
}
|
||||
},
|
||||
VitePWA({
|
||||
registerType: 'autoUpdate',
|
||||
includeAssets: ['lite.svg', 'robots.txt', 'sitemap.xml'],
|
||||
@@ -44,6 +54,21 @@ export default defineConfig({
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
// Frankfurter API 汇率缓存
|
||||
urlPattern: /^https:\/\/api\.frankfurter\.app\/.*/i,
|
||||
handler: 'StaleWhileRevalidate',
|
||||
options: {
|
||||
cacheName: 'currency-rates-cache',
|
||||
expiration: {
|
||||
maxEntries: 5,
|
||||
maxAgeSeconds: 60 * 60 * 12 // 12 小时
|
||||
},
|
||||
cacheableResponse: {
|
||||
statuses: [0, 200]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
// Google Fonts 样式表缓存
|
||||
urlPattern: /^https:\/\/fonts\.googleapis\.com\/.*/i,
|
||||
@@ -130,4 +155,4 @@ export default defineConfig({
|
||||
},
|
||||
chunkSizeWarningLimit: 500,
|
||||
},
|
||||
})
|
||||
}))
|
||||
|
||||
Reference in New Issue
Block a user