Files
web-temp/layers/server/routes/sitemap.xml.ts
2025-09-16 09:45:00 +09:00

68 lines
2.1 KiB
TypeScript

// server/routes/sitemap.xml.ts
type SitemapUrl = {
loc: string
lastmod?: string
changefreq?: 'always' | 'hourly' | 'daily' | 'weekly' | 'monthly' | 'yearly' | 'never'
priority?: number
}
type SitemapConfig = {
urls: SitemapUrl[]
cache?: { sMaxAge?: number; staleWhileRevalidate?: number }
}
export default defineEventHandler(async (event) => {
const host = (getHeader(event, "host") || getRequestHost(event)).toString() || "";
const baseDomain = process.env.BASE_DOMAIN || ".onstove.com";
const isGameAliasExtractable = host.includes(baseDomain);
let gameAlias = "";
if (isGameAliasExtractable) {
gameAlias = host.split(".")[0] || "";
}
let config: SitemapConfig;
try {
// 외부 API에서 sitemap 설정 가져오기
const response = await $fetch('https://static-pubcomm.gate8.com/dev/test0905/dataization/test0905_homepage_brand_siteConfig.json') as any;
// sitemap 설정에서 urls만 추출
const sitemapUrls = response.sitemap?.urls || [];
config = {
urls: sitemapUrls,
cache: { sMaxAge: 3600, staleWhileRevalidate: 7200 }
};
} catch (error) {
console.error('Failed to fetch sitemap config:', error);
// 에러 발생 시 빈 배열 반환
config = {
urls: [],
cache: { sMaxAge: 3600, staleWhileRevalidate: 7200 }
};
}
setHeader(event, "Content-Type", "application/xml; charset=utf-8");
// 캐시 헤더 (CDN 친화)
const sMax = config.cache?.sMaxAge ?? 3600;
const swr = config.cache?.staleWhileRevalidate ?? 7200;
setHeader(event, "Cache-Control", `public, s-maxage=${sMax}, stale-while-revalidate=${swr}`);
// XML 생성
const xml = `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
${config.urls.map(url => ` <url>
<loc>${url.loc}</loc>
${url.lastmod ? ` <lastmod>${url.lastmod}</lastmod>` : ''}
${url.changefreq ? ` <changefreq>${url.changefreq}</changefreq>` : ''}
${url.priority ? ` <priority>${url.priority}</priority>` : ''}
</url>`).join('\n')}
</urlset>`;
return xml;
});