From c35741c93c813a034c7ce004d90b634af5eadc01 Mon Sep 17 00:00:00 2001 From: DefectingCat Date: Mon, 5 Sep 2022 13:56:16 +0800 Subject: [PATCH] add static generate gist page --- next.config.mjs | 2 +- pages/g/[id].tsx | 45 +++++++++++++++++++++++++++++++++------------ 2 files changed, 34 insertions(+), 13 deletions(-) diff --git a/next.config.mjs b/next.config.mjs index 0738868..f4980ee 100644 --- a/next.config.mjs +++ b/next.config.mjs @@ -30,7 +30,7 @@ const nextConfig = { ? { allowFutureImage: true, unoptimized: true } : { allowFutureImage: true }, }, - assetPrefix: isExport ? './' : undefined, + // assetPrefix: isExport ? './' : undefined, // images: // process.env.NEXT_BUILD === 'export' // ? { diff --git a/pages/g/[id].tsx b/pages/g/[id].tsx index f4e0fcd..026fa7a 100644 --- a/pages/g/[id].tsx +++ b/pages/g/[id].tsx @@ -1,12 +1,13 @@ import Anchor from 'components/mdx/Anchor'; import dayjs from 'dayjs'; import relativeTime from 'dayjs/plugin/relativeTime'; -import { getSignalGist, SingalGist } from 'lib/fetcher'; +import { getGists, getSignalGist, SingalGist } from 'lib/fetcher'; import { GetStaticPaths, GetStaticProps, InferGetStaticPropsType } from 'next'; import dynamic from 'next/dynamic'; import Image from 'next/image'; import Link from 'next/link'; import avatar from 'public/images/img/avatar.svg'; +import { ParsedUrlQuery } from 'querystring'; import { ReactElement } from 'react'; const MainLayout = dynamic(() => import('layouts/MainLayout')); @@ -58,8 +59,23 @@ const Gist = ({ gist }: InferGetStaticPropsType) => { }; export const getStaticPaths: GetStaticPaths = async () => { + const result = await getGists(); + const next = Number(result?.pageSize.next); + const last = Number(result?.pageSize.last); + const paths: ( + | string + | { + params: ParsedUrlQuery; + locale?: string | undefined; + } + )[] = []; + for (let i = 1; i <= last; i++) { + const result = await getGists(i); + paths.push(...(result?.gists.map((g) => ({ params: { id: g.id } })) ?? [])); + } + return { - paths: [], + paths, fallback: 'blocking', }; }; @@ -73,19 +89,24 @@ export const getStaticProps: GetStaticProps<{ notFound: true, }; - const gist = await getSignalGist(params.id); - if (!gist || !gist.files) + try { + const gist = await getSignalGist(params.id); + if (!gist || !gist.files) + return { + notFound: true, + }; + return { + props: { + id: params?.id?.toString(), + gist, + }, + revalidate: 600, + }; + } catch (err) { return { notFound: true, }; - - return { - props: { - id: params?.id?.toString(), - gist, - }, - revalidate: 600, - }; + } }; Gist.getLayout = function getLayout(page: ReactElement) {