Skip to content

Commit

Permalink
feat: 修改获取信息逻辑,改为缓存文件获取
Browse files Browse the repository at this point in the history
  • Loading branch information
coderz-w committed Nov 12, 2024
1 parent fc87921 commit df6ee64
Show file tree
Hide file tree
Showing 10 changed files with 165 additions and 67 deletions.
32 changes: 16 additions & 16 deletions markdown/index.json
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
[
{
"authors": ["yy"],
"path": "yyblog.md",
"title": "yyblog",
"tag": "技术/react",
"coverImage": "https://p6-xtjj-sign.byteimg.com/tos-cn-i-73owjymdk6/0b76076eab124179816d68b846280cdc~tplv-73owjymdk6-jj-mark-v1:0:0:0:0:5o6Y6YeR5oqA5pyv56S-5Yy6IEAgTWVnYXRyb25LaW5n:q75.awebp?rk3s=f64ab15b&x-expires=1731736114&x-signature=3ggdE9od5WvMZaVJ7VFlQtt48rA%3D"
},
{
"authors": ["yy"],
"path": "react19.md",
"title": "react19",
"tag": "随笔/生活",
"summary": "这篇文章记录了react19相关的一些内容",
"coverImage": "https://p6-xtjj-sign.byteimg.com/tos-cn-i-73owjymdk6/0b76076eab124179816d68b846280cdc~tplv-73owjymdk6-jj-mark-v1:0:0:0:0:5o6Y6YeR5oqA5pyv56S-5Yy6IEAgTWVnYXRyb25LaW5n:q75.awebp?rk3s=f64ab15b&x-expires=1731736114&x-signature=3ggdE9od5WvMZaVJ7VFlQtt48rA%3D"
}
]
{
"authors": ["yy"],
"path": "yyblog.md",
"title": "yyblog",
"tag": "技术/react",
"coverImage": "https://p6-xtjj-sign.byteimg.com/tos-cn-i-73owjymdk6/0b76076eab124179816d68b846280cdc~tplv-73owjymdk6-jj-mark-v1:0:0:0:0:5o6Y6YeR5oqA5pyv56S-5Yy6IEAgTWVnYXRyb25LaW5n:q75.awebp?rk3s=f64ab15b&x-expires=1731736114&x-signature=3ggdE9od5WvMZaVJ7VFlQtt48rA%3D"
},
{
"authors": ["yy"],
"path": "react19.md",
"title": "react19",
"tag": "随笔/生活",
"summary": "这篇文章记录了react19相关的一些内容",
"coverImage": "https://p6-xtjj-sign.byteimg.com/tos-cn-i-73owjymdk6/0b76076eab124179816d68b846280cdc~tplv-73owjymdk6-jj-mark-v1:0:0:0:0:5o6Y6YeR5oqA5pyv56S-5Yy6IEAgTWVnYXRyb25LaW5n:q75.awebp?rk3s=f64ab15b&x-expires=1731736114&x-signature=3ggdE9od5WvMZaVJ7VFlQtt48rA%3D"
}
]
72 changes: 72 additions & 0 deletions markdown/output.json

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions src/app/(app)/(home)/page.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { buildPostData } from '@/core';
import { getPostData } from '@/core';
import { FocusCards } from '@/components/ui/focus-cards.tsx';
import { Hero } from '@/components/modules/home/Hero';
import { WindVane } from '@/components/modules/home/WindVane/WindVane';

const { postDataList } = buildPostData();
const { postDataList } = await getPostData();

export default function Home() {
return (
Expand Down
6 changes: 3 additions & 3 deletions src/app/(app)/list/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,15 @@ import { Metadata } from 'next';
import AnimatedPostItem from './AnimatedPostItem';

import { NormalContainer } from '@/components/layout/container/Normal';
import { buildPostData } from '@/core';
import { getPostData } from '@/core';

export const metadata: Metadata = {
title: '文稿',
description: '文章列表',
};

const ArticleList: React.FC = () => {
const { postDataList } = buildPostData();
const ArticleList: React.FC = async () => {
const { postDataList } = await getPostData();

return (
<NormalContainer>
Expand Down
4 changes: 2 additions & 2 deletions src/app/(app)/notes/[nid]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,12 @@ import {
PageTransition,
} from './pageExtra';

import { type PostItem as PostItemType, buildPostData } from '@/core';
import { type PostItem as PostItemType, getPostData } from '@/core';
import { LayoutRightSidePortal } from '@/providers/shared/LayoutRightSideProvider';
import { ArticleRightAside } from '@/components/modules/shared/ArticleRightAside';
import { Signature } from '@/components/modules/shared/signature';

const { postDataMap } = buildPostData();
const { postDataMap } = await getPostData();

export type PageInnerProps = { postData: PostItemType };

Expand Down
4 changes: 2 additions & 2 deletions src/app/feed.xml/route.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ import RSS from 'rss';
import { compiler } from 'markdown-to-jsx';

import { siteUrl, seo } from '~/seo';
import { buildPostData } from '@/core';
import { getPostData } from '@/core';

const { postDataList } = buildPostData();
const { postDataList } = await getPostData();

export async function GET() {
const ReactDOM = (await import('react-dom/server')).default;
Expand Down
4 changes: 2 additions & 2 deletions src/app/sitemap.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { MetadataRoute } from 'next';

import { siteUrl } from '~/seo';
import { buildPostData } from '@/core';
import { getPostData } from '@/core';

const { postDataList } = buildPostData();
const { postDataList } = await getPostData();

export default function sitemap(): MetadataRoute.Sitemap {
const postSitemap = postDataList.map((post) => ({
Expand Down
4 changes: 2 additions & 2 deletions src/components/layout/Header/Header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ import { HeaderMeta } from './HeaderMeta';
import { HeaderDrawerButton } from './HeaderDrawerButton';

import { cn } from '@/lib/helper';
import { buildPostData } from '@/core';
import { getPostData } from '@/core';

const { postDataMap } = buildPostData();
const { postDataMap } = await getPostData();

const Header = () => {
return (
Expand Down
100 changes: 63 additions & 37 deletions src/core/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import jsonData from '@md/index.json';
import { join } from 'node:path';
import { existsSync, writeFileSync } from 'node:fs';

import { symbolsTime, symbolsCount } from '@/lib/count';
import { getFirstGitCommitTime, getLastGitUpdateTime } from '@/lib/git';
Expand Down Expand Up @@ -28,58 +29,83 @@ export type PostJsonType = {
coverImage: string;
summary?: string;
};

export type PostMap = Record<string, PostItem>;

export function importMarkdownFile(path: string) {
// 使用 require.context 获取所有 markdown 文件
const markdownContext = (require as any).context('../../markdown', true, /\.md$/);

return markdownContext(path);
}

export function importJsonFile(path: string) {
const jsonContext = (require as any).context('../../markdown', true, /\.json$/);

return jsonContext(path);
}

export function writeOutputFile(data: { postDataMap: PostMap; postDataList: PostItem[] }) {
const outputContent = {
postDataMap: data.postDataMap,
postDataList: data.postDataList,
};

const outputPath = join(process.cwd(), 'markdown/output.json');
writeFileSync(outputPath, JSON.stringify(outputContent, null, 2));

console.log(`Data written to ${outputPath}`);
}

export function buildPostData() {
const postDataMap: PostMap = {};
const postDataList: PostItem[] = [];

function processPostItem(item: PostJsonType) {
const itemInfo = {} as PostItem;
const file = importMarkdownFile(`./${item.path}`);
itemInfo.authors = item.authors;
itemInfo.title = item.title;
itemInfo.tag = item.tag;
itemInfo.path = item.path.replace('.md', '');
itemInfo.rawFilePath = `./${item.path}`;
itemInfo.summary = item.summary;
itemInfo.coverImage = item.coverImage.startsWith('http')
? item.coverImage
: `/postCoverImage/${item.coverImage}`;

itemInfo.text = file;
itemInfo.count = symbolsCount(file);
itemInfo.readingTime = symbolsTime(file, 0, 200);
itemInfo.updatedAt = getLastGitUpdateTime(join('markdown/', item.path));
itemInfo.createdAt = getFirstGitCommitTime(join('markdown/', item.path));

itemInfo.modified =
itemInfo.updatedAt && itemInfo.createdAt
? itemInfo.updatedAt.getTime() !== itemInfo.createdAt.getTime()
: false;

postDataMap[itemInfo.path] = itemInfo;
postDataList.push(itemInfo);
function processPostItem({ authors, title, tag, path, coverImage, summary }: PostJsonType) {
const file = importMarkdownFile(`./${path}`);
const createdAt = getFirstGitCommitTime(join('markdown/', path));
const updatedAt = getLastGitUpdateTime(join('markdown/', path));

const postItem: PostItem = {
authors,
title,
tag,
path: path.replace('.md', ''),
rawFilePath: `./${path}`,
summary,
coverImage: coverImage.startsWith('http') ? coverImage : `/postCoverImage/${coverImage}`,
text: file,
count: symbolsCount(file),
readingTime: symbolsTime(file, 0, 200),
createdAt,
updatedAt,
modified: updatedAt && createdAt ? updatedAt.getTime() !== createdAt.getTime() : false,
};

postDataMap[postItem.path] = postItem;
postDataList.push(postItem);
}

jsonData.forEach((postJsonItem: PostJsonType) => {
processPostItem(postJsonItem);
});
jsonData.forEach((postJsonItem) => processPostItem(postJsonItem));

postDataList.sort((a, b) => (b.createdAt?.getTime() || 0) - (a.createdAt?.getTime() || 0));

const result = { postDataMap, postDataList };
writeOutputFile(result);

postDataList.sort((a, b) => {
if (a.createdAt && b.createdAt) {
return b.createdAt.getTime() - a.createdAt.getTime();
}
return result;
}

export async function getPostData(): Promise<{ postDataMap: PostMap; postDataList: PostItem[] }> {
const outputPath = join(process.cwd(), 'markdown/output.json');

return 0;
});
if (existsSync(outputPath)) {
const { postDataMap, postDataList } = importJsonFile('./output.json');
console.log('Using cached post data.');

return { postDataMap, postDataList };
return { postDataMap, postDataList };
} else {
console.log('Output file not found, generating post data...');

return buildPostData();
}
}
2 changes: 1 addition & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"compilerOptions": {
"lib": ["dom", "dom.iterable", "esnext"],
"target": "es2015",
"target": "es2017",
"allowJs": true,
"skipLibCheck": true,
"strict": true,
Expand Down

0 comments on commit df6ee64

Please sign in to comment.