Skip to content

Commit

Permalink
feat(blog): make category SSR
Browse files Browse the repository at this point in the history
  • Loading branch information
Soulike committed Sep 8, 2024
1 parent 38c4190 commit 58ea245
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 16 deletions.
16 changes: 16 additions & 0 deletions apps/blog/src/app/category/[id]/CategoryViewModel.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import {Article} from '@website/classes';

import {Article as ArticleApi} from '@/src/apis';

export class CategoryViewModel {
public static async getArticlesWithAbstractByCategory(
categoryId: number,
): Promise<Article[]> {
const response = await ArticleApi.getByCategoryWithAbstract(categoryId);
if (response.isSuccessful) {
return response.data;
} else {
throw new Error(response.message);
}
}
}
33 changes: 17 additions & 16 deletions apps/blog/src/app/category/[id]/Container.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
'use client';

import {useEffect} from 'react';
import {notFound} from 'next/navigation';

import {ArticleList} from '@/src/components/ArticleList';
import {useArticlesWithAbstract} from '@/src/hooks/useArticlesWithAbstract';

import {CategoryViewModel} from './CategoryViewModel';

interface CategoryProps {
params: CategoryDynamicParams;
Expand All @@ -13,17 +12,19 @@ interface CategoryDynamicParams {
id: string;
}

export function Category({params}: CategoryProps) {
export async function Category({params}: CategoryProps) {
const {id} = params;
const categoryId = Number.parseInt(id ?? '');

useEffect(() => {
document.title = 'Soulike 的博客';
}, []);

const {loading, articlesWithAbstract} = useArticlesWithAbstract(categoryId);

return (
<ArticleList articleList={articlesWithAbstract ?? []} loading={loading} />
);
const categoryId = Number.parseInt(id);
if (Number.isNaN(categoryId)) {
notFound();
}

try {
const articlesWithAbstract =
await CategoryViewModel.getArticlesWithAbstractByCategory(categoryId);
return <ArticleList articleList={articlesWithAbstract} loading={false} />;
} catch (e) {
console.error(e);
notFound();
}
}
6 changes: 6 additions & 0 deletions apps/blog/src/app/category/[id]/page.tsx
Original file line number Diff line number Diff line change
@@ -1 +1,7 @@
import type {Metadata} from 'next';

export {Category as default} from './Container';

export const metadata: Metadata = {
title: 'Soulike 的博客',
};

0 comments on commit 58ea245

Please sign in to comment.