import { NextApiRequest, NextApiResponse } from 'next'; import { getSortedSitesData } from '@/lib/Site';

export default async function handler( req: NextApiRequest, res: NextApiResponse ) { const { numCategories } = await getSortedSitesData(); res.status(200).json({ numCategories }); }

// 统计共有多少个分类 import fs from 'fs' import path from 'path' import matter from 'gray-matter' import Info from '@/components/Info'

export const info = Info(); export const Directory = path.join(process.cwd(), info.path)

export async function getSortedSitesData() {

const subdirectories = fs.readdirSync(Directory, { withFileTypes: true }) .filter(dirent => dirent.isDirectory()) .map(dirent => dirent.name)

const posts = (await Promise.all(subdirectories.map(async (subdirectory) => { const directoryPath = path.join(Directory, subdirectory) const filenames = fs.readdirSync(directoryPath) .filter(filename => filename.endsWith('.md'))

  const allPostsData = await Promise.all(filenames.map(async (filename) => {
    const fullPath = path.join(Directory, [subdirectory, filename].join('//'))
    const fileContents = fs.readFileSync(fullPath, 'utf8')
    const matterResult = matter(fileContents)
    const postData = {
        ...(matterResult.data as { name: string, link: string, icon: string, desc: string, sort: string, star: string, }),
    };

    return postData;
}))
const sortedPostsData = allPostsData.reduce((acc, elems) => {
    if(Array.isArray(elems)) {
        return acc.concat(elems);
    }
    acc.push(elems);
    return acc;
}, []);
return sortedPostsData.sort((a, b) => {
    if (a.date < b.date) {
        return 1
    } else {
        return -1
    }
})

}))).flat()

const categories = new Set(posts.map((post) => post.sort)); const numCategories = categories.size;

return { posts, numCategories, }; }

// 统计 sort 的分类有几个内容:To count how many categories there are in the 'sort' field, you can modify the getSortedSitesData function to create an array of all the unique 'sort' values and then return the length of that array. Here's an example of how you could modify the function:

export async function getSortedSitesData() {
  // ... existing code to read and parse files ...

  const categories = new Set(allPostsData.map((post) => post.sort));
  const numCategories = categories.size;

  return {
    posts: sortedPostsData,
    numCategories,
  };
}

This will return an object with two properties: posts, which is the sorted array of post data, and numCategories, which is the number of unique categories found in the 'sort' field. You can then use the numCategories value in your API route to return the count:

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  const { numCategories } = await getSortedSitesData();
  res.status(200).json({ numCategories });
}
统计 Next.js 应用中分类的数量

原文地址: https://www.cveoy.top/t/topic/mZxs 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录