5 Commits

Author SHA1 Message Date
typist
1a00f27c6a 0.0.33
All checks were successful
Build and Push Docker Image / build (push) Successful in 1m37s
2025-10-30 09:49:41 +08:00
typist
1bcbd3e37d feat: implement caching for Frankfurter API exchange rates
- Added a caching strategy for the Frankfurter API using Service Worker with StaleWhileRevalidate.
- Removed the local storage caching logic from the currency tool to streamline data fetching.
- Updated the currency tool to rely on the Service Worker for managing exchange rate data.
2025-10-30 09:49:30 +08:00
typist
e88770dd3f fix: remove unused date property from cached rates in currency tool
- Updated the currency tool to eliminate the unused 'date' property from the cached rates object, streamlining the data structure.
2025-10-30 09:45:15 +08:00
typist
5cef15c032 0.0.32
Some checks failed
Build and Push Docker Image / build (push) Failing after 1m12s
2025-10-30 09:44:05 +08:00
typist
970d1ac3ed feat: conditionally inject Cloudflare Analytics script
- Updated index.html to include a placeholder for Cloudflare Web Analytics, which is now only injected in production mode.
- Modified vite.config.ts to implement an HTML transform plugin that dynamically adds the Cloudflare script based on the environment.
2025-10-30 09:43:50 +08:00
4 changed files with 37 additions and 68 deletions

View File

@@ -65,8 +65,8 @@
<div id="root"></div> <div id="root"></div>
<script type="module" src="/src/main.tsx"></script> <script type="module" src="/src/main.tsx"></script>
<!-- Cloudflare Web Analytics --> <!-- Cloudflare Web Analytics - Only in Production -->
<script defer src='https://static.cloudflareinsights.com/beacon.min.js' data-cf-beacon='{"token": "2aecdc025eb043bc89ce931b54a80054"}'></script> <!--CLOUDFLARE_ANALYTICS_PLACEHOLDER-->
<!-- End Cloudflare Web Analytics --> <!-- End Cloudflare Web Analytics -->
</body> </body>
</html> </html>

View File

@@ -1,7 +1,7 @@
{ {
"name": "litek", "name": "litek",
"private": true, "private": true,
"version": "0.0.31", "version": "0.0.33",
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",

View File

@@ -53,7 +53,6 @@ const AVAILABLE_CURRENCIES: Currency[] = [
const REQUIRED_CURRENCIES = ["USD", "CNY"]; const REQUIRED_CURRENCIES = ["USD", "CNY"];
const STORAGE_KEY = "selectedCurrencies"; const STORAGE_KEY = "selectedCurrencies";
const RATES_CACHE_KEY = "currencyRatesCache";
const Tool: FC = () => { const Tool: FC = () => {
const [amounts, setAmounts] = useState<Record<string, string>>({}); const [amounts, setAmounts] = useState<Record<string, string>>({});
@@ -91,42 +90,13 @@ const Tool: FC = () => {
} }
}, [selectedCurrencies]); }, [selectedCurrencies]);
// Fetch exchange rates with date-based caching // Fetch exchange rates (Service Worker handles caching)
useEffect(() => { useEffect(() => {
const fetchRates = async () => { const fetchRates = async () => {
try { try {
// 1. Try to load from cache
const cached = localStorage.getItem(RATES_CACHE_KEY);
if (cached) {
try {
const { rates: cachedRates, date: cachedDate, fetchedAt } = JSON.parse(cached);
const now = Date.now();
const twelveHoursInMs = 12 * 60 * 60 * 1000;
// Strategy: Use cache if it's recent enough (within 12 hours)
// This handles all edge cases: weekends, holidays, timezone differences
// Exchange rates update once per day, so 12-hour cache is reasonable
if (fetchedAt && (now - fetchedAt < twelveHoursInMs)) {
setRates(cachedRates);
setLoading(false);
return;
} else {
// Cache is older than 12 hours, show it 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); setLoading(true);
const response = await fetch("https://api.frankfurter.app/latest?base=USD", { // Service Worker will handle caching with StaleWhileRevalidate strategy
cache: "no-cache", const response = await fetch("https://api.frankfurter.app/latest?base=USD");
});
if (!response.ok) { if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`); throw new Error(`HTTP error! status: ${response.status}`);
@@ -134,40 +104,14 @@ const Tool: FC = () => {
const data = await response.json(); const data = await response.json();
const allRates: Record<string, number> = { USD: 1, ...data.rates }; 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 (with timestamp)
setRates(allRates); setRates(allRates);
localStorage.setItem(
RATES_CACHE_KEY,
JSON.stringify({
rates: allRates,
date: apiDate,
fetchedAt: Date.now() // Timestamp when we fetched the data
})
);
} catch (error) { } catch (error) {
// If cache exists, continue using it even if network fails console.error("Failed to fetch rates:", error);
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);
if (error instanceof Error) { if (error instanceof Error) {
toast.error(`Failed to fetch rates: ${error.message}`); toast.error(`Failed to fetch exchange rates: ${error.message}`);
} else { } else {
toast.error("Failed to fetch rates"); toast.error("Failed to fetch exchange rates");
}
}
} else {
if (error instanceof Error) {
toast.error(`Failed to fetch rates: ${error.message}`);
} else {
toast.error("Failed to fetch rates");
}
} }
} finally { } finally {
setLoading(false); setLoading(false);

View File

@@ -5,10 +5,20 @@ import tailwindcss from "@tailwindcss/vite"
import { VitePWA } from 'vite-plugin-pwa' import { VitePWA } from 'vite-plugin-pwa'
// https://vite.dev/config/ // https://vite.dev/config/
export default defineConfig({ export default defineConfig(({ mode }) => ({
plugins: [ plugins: [
react(), react(),
tailwindcss(), 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({ VitePWA({
registerType: 'autoUpdate', registerType: 'autoUpdate',
includeAssets: ['lite.svg', 'robots.txt', 'sitemap.xml'], 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 样式表缓存 // Google Fonts 样式表缓存
urlPattern: /^https:\/\/fonts\.googleapis\.com\/.*/i, urlPattern: /^https:\/\/fonts\.googleapis\.com\/.*/i,
@@ -130,4 +155,4 @@ export default defineConfig({
}, },
chunkSizeWarningLimit: 500, chunkSizeWarningLimit: 500,
}, },
}) }))