clone init
This commit is contained in:
44
lib/mdx.ts
Normal file
44
lib/mdx.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
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);
|
||||
const filePath = path.join(productsDir, `${slug}.mdx`);
|
||||
|
||||
if (!fs.existsSync(filePath)) {
|
||||
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$/, ''));
|
||||
}
|
||||
Reference in New Issue
Block a user