Some checks failed
thehideout/TheHideout-API/pipeline/head There was a failure building this commit
95 lines
2.8 KiB
JavaScript
95 lines
2.8 KiB
JavaScript
import { processNotionIcon } from "./icon";
|
|
|
|
export async function getNavigation(env, cached = false) {
|
|
try {
|
|
// If cached=true, try to get from Cloudflare Cache API first
|
|
if (cached) {
|
|
try {
|
|
const cache = caches.default;
|
|
const cacheKey = new Request(
|
|
`https://${env.NAVIGATION_CACHE_URL || "cache"}/navigation`
|
|
);
|
|
const cachedResponse = await cache.match(cacheKey);
|
|
|
|
if (cachedResponse) {
|
|
const cachedData = await cachedResponse.json();
|
|
console.log("Navigation retrieved from Cloudflare cache");
|
|
return cachedData;
|
|
}
|
|
} catch (cacheError) {
|
|
console.log("Cache miss or error, falling back to KV:", cacheError);
|
|
}
|
|
}
|
|
|
|
// Fall back to KV storage
|
|
const kvData = await env.CONTENT_KV.get(env.NAVIGATION_KEY, {
|
|
type: "json",
|
|
});
|
|
return kvData || null;
|
|
} catch (error) {
|
|
console.log("Error fetching navigation cache:", error);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
export async function storeNavigation(env, navigation) {
|
|
try {
|
|
// Always store in KV first
|
|
await env.CONTENT_KV.put(env.NAVIGATION_KEY, JSON.stringify(navigation));
|
|
console.log("Navigation stored in KV.");
|
|
|
|
// Also update the Cloudflare Cache API
|
|
try {
|
|
const cache = caches.default;
|
|
const cacheKey = new Request(
|
|
`https://${env.NAVIGATION_CACHE_URL || "cache"}/navigation`
|
|
);
|
|
|
|
// Create a response with appropriate cache headers
|
|
const response = new Response(JSON.stringify(navigation), {
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
"Cache-Control": "max-age=60", // 1 minute TTL
|
|
ETag: `"navigation-${Date.now()}"`, // Add ETag for cache validation
|
|
},
|
|
});
|
|
|
|
await cache.put(cacheKey, response);
|
|
console.log("Navigation stored in Cloudflare cache.");
|
|
} catch (cacheError) {
|
|
console.warn(
|
|
"Error updating Cloudflare cache, but KV was updated successfully:",
|
|
cacheError
|
|
);
|
|
}
|
|
} catch (error) {
|
|
console.error("Error storing navigation cache:", error);
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
// Transform basic Notion page data to desired format
|
|
export async function transformNavigation(notionPage, type) {
|
|
var icon = undefined;
|
|
if (notionPage.icon) {
|
|
try {
|
|
icon = await processNotionIcon(notionPage.icon, "th-icon");
|
|
} catch (error) {
|
|
console.error("Error processing navigation icon:", error);
|
|
}
|
|
}
|
|
const properties = notionPage.properties;
|
|
const id = notionPage.id;
|
|
const slug = properties.Slug?.formula?.string || "unknown";
|
|
// Extract name from title
|
|
const name = properties.Name?.title?.[0]?.plain_text || "Untitled";
|
|
|
|
return {
|
|
slug: type == "property" ? `properties/${slug}` : slug,
|
|
name: name,
|
|
icon: icon,
|
|
notionId: id,
|
|
type: type,
|
|
};
|
|
}
|