Files

52 lines
1.6 KiB
TypeScript

import path from 'node:path'
import fs from 'node:fs'
import staticContent from '@/content/site-content.json'
/**
* نوع کلی محتوای سایت.
* با تغییر فایل content/site-content.json یا public/content.json
* می‌توان بدون بیلد مجدد متن‌ها و تصاویر را عوض کرد.
*/
export type SiteContent = typeof staticContent
/**
* محتوای پیش‌فرض (از content/site-content.json در بیلد).
*/
export const defaultContent: SiteContent = staticContent as SiteContent
/**
* خواندن محتوای سایت.
* در سرور ابتدا public/content.json را امتحان می‌کند (برای تغییر بدون بیلد)،
* در صورت نبود یا خطا از محتوای پیش‌فرض استفاده می‌کند.
*/
export async function getContent(): Promise<SiteContent> {
if (typeof window !== 'undefined') {
return defaultContent
}
try {
const publicPath = path.join(process.cwd(), 'public', 'content.json')
const raw = fs.readFileSync(publicPath, 'utf-8')
const parsed = JSON.parse(raw) as SiteContent
return parsed
} catch {
return defaultContent
}
}
/**
* نسخهٔ همگام برای استفاده در Server Components که await پشتیبانی نمی‌کنند.
*/
export function getContentSync(): SiteContent {
if (typeof window !== 'undefined') {
return defaultContent
}
try {
const publicPath = path.join(process.cwd(), 'public', 'content.json')
const raw = fs.readFileSync(publicPath, 'utf-8')
return JSON.parse(raw) as SiteContent
} catch {
return defaultContent
}
}