Files
klz-cables.com/lib/mdx.ts
2026-01-17 13:17:10 +01:00

79 lines
2.3 KiB
TypeScript

import fs from 'fs';
import path from 'path';
import matter from 'gray-matter';
export interface ProductFrontmatter {
title: string;
sku: string;
description: string;
categories: string[];
images: string[];
locale: string;
}
export interface ProductMdx {
slug: string;
frontmatter: ProductFrontmatter;
content: string;
}
export async function getProductBySlug(slug: string, locale: string): Promise<ProductMdx | null> {
const productsDir = path.join(process.cwd(), 'data', 'products', locale);
// Try exact slug first
let filePath = path.join(productsDir, `${slug}.mdx`);
if (!fs.existsSync(filePath)) {
// Try with -2 suffix (common in the dumped files)
filePath = path.join(productsDir, `${slug}-2.mdx`);
}
if (!fs.existsSync(filePath)) {
// Fallback to English if locale is not 'en'
if (locale !== 'en') {
const enProductsDir = path.join(process.cwd(), 'data', 'products', 'en');
let enFilePath = path.join(enProductsDir, `${slug}.mdx`);
if (!fs.existsSync(enFilePath)) {
enFilePath = path.join(enProductsDir, `${slug}-2.mdx`);
}
if (fs.existsSync(enFilePath)) {
const fileContent = fs.readFileSync(enFilePath, 'utf8');
const { data, content } = matter(fileContent);
return {
slug,
frontmatter: {
...data,
isFallback: true
} as ProductFrontmatter & { isFallback?: boolean },
content,
};
}
}
return null;
}
const fileContent = fs.readFileSync(filePath, 'utf8');
const { data, content } = matter(fileContent);
return {
slug,
frontmatter: data as ProductFrontmatter,
content,
};
}
export async function getAllProductSlugs(locale: string): Promise<string[]> {
const productsDir = path.join(process.cwd(), 'data', 'products', locale);
if (!fs.existsSync(productsDir)) return [];
const files = fs.readdirSync(productsDir);
return files.filter(file => file.endsWith('.mdx')).map(file => file.replace(/\.mdx$/, ''));
}
export async function getAllProducts(locale: string): Promise<ProductMdx[]> {
const slugs = await getAllProductSlugs(locale);
const products = await Promise.all(slugs.map(slug => getProductBySlug(slug, locale)));
return products.filter((p): p is ProductMdx => p !== null);
}