init
This commit is contained in:
57
lib/getProducts.ts
Normal file
57
lib/getProducts.ts
Normal file
@@ -0,0 +1,57 @@
|
||||
import { DEFAULT_LOCALE } from '@/i18n/routing';
|
||||
import { Product } from '@/types/product';
|
||||
import fs from 'fs';
|
||||
import matter from 'gray-matter';
|
||||
import path from 'path';
|
||||
|
||||
const POSTS_BATCH_SIZE = 10;
|
||||
|
||||
export async function getProducts(locale: string = DEFAULT_LOCALE): Promise<{ products: Product[] }> {
|
||||
const postsDirectory = path.join(process.cwd(), 'content', 'product', locale);
|
||||
|
||||
// is directory exist
|
||||
if (!fs.existsSync(postsDirectory)) {
|
||||
return { products: [] };
|
||||
}
|
||||
|
||||
let filenames = await fs.promises.readdir(postsDirectory);
|
||||
filenames = filenames.reverse();
|
||||
|
||||
let allPosts: Product[] = [];
|
||||
|
||||
// read file by batch
|
||||
for (let i = 0; i < filenames.length; i += POSTS_BATCH_SIZE) {
|
||||
const batchFilenames = filenames.slice(i, i + POSTS_BATCH_SIZE);
|
||||
|
||||
const batchPosts: Product[] = await Promise.all(
|
||||
batchFilenames.map(async (filename) => {
|
||||
const fullPath = path.join(postsDirectory, filename);
|
||||
const fileContents = await fs.promises.readFile(fullPath, 'utf8');
|
||||
|
||||
const { data, content } = matter(fileContents);
|
||||
console.log(data);
|
||||
|
||||
return {
|
||||
locale, // use locale parameter
|
||||
title: data.title,
|
||||
model: data.model,
|
||||
place: data.place,
|
||||
publishedTime: data.publishedTime,
|
||||
images: data.images || [],
|
||||
detail: data.detail,
|
||||
spec: data.spec || [],
|
||||
packaging: data.packaging || '',
|
||||
slug: data.slug || '',
|
||||
content,
|
||||
metadata: data,
|
||||
};
|
||||
})
|
||||
);
|
||||
|
||||
allPosts.push(...batchPosts);
|
||||
}
|
||||
|
||||
return {
|
||||
products: allPosts,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user