Skip to content

Commit

Permalink
feat: upgrade nextjs & bug fix
Browse files Browse the repository at this point in the history
1. upgrade Next to version 14
2. SSG supported
  • Loading branch information
alex-guoba committed Jan 11, 2024
1 parent 4e05ca3 commit 1eda3b1
Show file tree
Hide file tree
Showing 11 changed files with 3,339 additions and 111 deletions.
16 changes: 16 additions & 0 deletions app/article/[slug]/layout.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
export default function ArticleLayout({
children, // will be a page or nested layout
}: {
children: React.ReactNode
}) {
return (
<div>
{/* Include shared UI here e.g. a header or sidebar */}
{/* <seciton className="w-full flex-none md:w-64">
<SideNav />
</seciton> */}

<div className="grow p-6 md:overflow-y-auto md:p-12">{children}</div>
</div>
)
}
56 changes: 56 additions & 0 deletions app/article/[slug]/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import Head from "next/head";
import Link from "next/link";
import { Fragment } from "react";
import Text from "@/app/ui/text";

import {renderBlock} from "@/app/ui/notion/render";
import { getDatabase, getPageFromSlug, getBlocks } from "@/app/lib/notion";

// https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config#revalidate
export const revalidate = 60; // revalidate the data at most every hour

// export const dynamicParams = true; // true | false,

// Return a list of `params` to populate the [slug] dynamic segment
export async function generateStaticParams() {

const database = await getDatabase();

return database.map((page: any) => {
const slug = page.properties.Slug?.rich_text[0].plain_text;
return ({ slug });
});
}

export default async function Page({ params }: {params: {slug: string}}) {
console.log(params)
const page: any = await getPageFromSlug(params.slug);
const blocks = page && await getBlocks(page.id);

if (!page || !blocks) {
return <div />;
}

return (
<div>
<Head>
<title>{page.properties.Title?.title[0].plain_text}</title>
<link rel="icon" href="/favicon.ico" />
</Head>

<article>
<h1>
<Text title={page.properties.Title?.title} />
</h1>
<section>
{blocks.map((block: any) => (
<Fragment key={block.id}>{renderBlock(block)}</Fragment>
))}
<Link href="/">
← Go home
</Link>
</section>
</article>
</div>
);
}
Binary file removed app/favicon.ico
Binary file not shown.
1 change: 1 addition & 0 deletions app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import './globals.css'

const inter = Inter({ subsets: ['latin'] })

// use tempated metadata
export const metadata: Metadata = {
title: 'Create Next App',
description: 'Generated by create next app',
Expand Down
132 changes: 132 additions & 0 deletions app/lib/notion.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
import { Client } from '@notionhq/client';
import { cache } from 'react';
import {QueryDatabaseResponse, ListBlockChildrenResponse} from '@notionhq/client/build/src/api-endpoints';


const databaseId = process.env.NOTION_DATABASE_ID || '';

/**
* Returns a random integer between the specified values, inclusive.
* The value is no lower than `min`, and is less than or equal to `max`.
*
* @param {number} minimum - The smallest integer value that can be returned, inclusive.
* @param {number} maximum - The largest integer value that can be returned, inclusive.
* @returns {number} - A random integer between `min` and `max`, inclusive.
*/
function getRandomInt(minimum: number, maximum: number): number {
const min = Math.ceil(minimum);
const max = Math.floor(maximum);
return Math.floor(Math.random() * (max - min + 1)) + min;
}

const notion = new Client({
auth: process.env.NOTION_TOKEN,
});

// 取db中的pages列表数据(posts)
// API: https://developers.notion.com/reference/post-database-query
export const getDatabase = cache(async (): Promise<QueryDatabaseResponse['results']> => {
const start = new Date().getTime();

const response = await notion.databases.query({
database_id: databaseId,
});
const end = new Date().getTime();
console.log('[getDatabase]', `${end - start}ms`);
return response.results;
});

//
// 读取一个page的基础数据(page object)
// API: https://developers.notion.com/reference/retrieve-a-page
export const getPage = cache(async (pageId: any) => {
const start = new Date().getTime();
const response = await notion.pages.retrieve({ page_id: pageId });
const end = new Date().getTime();
console.log('[getPage]', `${end - start}ms`);
return response;
});

//
// slug:(计算机)处理后的标题(用于构建固定链接)
// 根据标题取db中的page列表数据,限制一条
export const getPageFromSlug = cache(async (slug: string) => {
const start = new Date().getTime();

const response = await notion.databases.query({
database_id: databaseId,
filter: {
property: 'Slug',
formula: {
string: {
equals: slug,
},
},
},
});
const end = new Date().getTime();
console.log('[getPageFromSlug]', `${end - start}ms`);

if (response?.results?.length) {
return response?.results?.[0];
}
});

//
// 取page/block的children列表数据 (blocks)
export const getBlocks = cache(async (blockID: string): Promise<any> => {
const start = new Date().getTime();

const blockId = blockID.replaceAll('-', '');

// 只读取了100条,超过100时没有取完
const { results } = await notion.blocks.children.list({
block_id: blockId,
page_size: 100,
});

// Fetches all child blocks recursively
// be mindful of rate limits if you have large amounts of nested blocks
// See https://developers.notion.com/docs/working-with-page-content#reading-nested-blocks
// 递归取child blocks,嵌套block量大时会有风险。
const childBlocks = results.map(async (block: any) => {
if (block.has_children) {
const children = await getBlocks(block.id);
return { ...block, children };
}

return block;
});

const end = new Date().getTime();
console.log('[getBlocks]', `${end - start}ms`);

return Promise.all(childBlocks).then((blocks) => blocks.reduce((acc, curr) => {
// 符号列表类型的特殊处理:转换为parent -> {children} 结构,并增加uniqID(更加方便渲染?)
// https://developers.notion.com/reference/block#bulleted-list-item
if (curr.type === 'bulleted_list_item') {
if (acc[acc.length - 1]?.type === 'bulleted_list') {
acc[acc.length - 1][acc[acc.length - 1].type].children?.push(curr);
} else {
acc.push({
id: getRandomInt(10 ** 99, 10 ** 100).toString(),
type: 'bulleted_list',
bulleted_list: { children: [curr] },
});
}
} else if (curr.type === 'numbered_list_item') {
if (acc[acc.length - 1]?.type === 'numbered_list') {
acc[acc.length - 1][acc[acc.length - 1].type].children?.push(curr);
} else {
acc.push({
id: getRandomInt(10 ** 99, 10 ** 100).toString(),
type: 'numbered_list',
numbered_list: { children: [curr] },
});
}
} else {
acc.push(curr);
}
return acc;
}, []));
});
157 changes: 51 additions & 106 deletions app/page.tsx
Original file line number Diff line number Diff line change
@@ -1,113 +1,58 @@
import Image from 'next/image'
// import Image from 'next/image'
import Link from 'next/link';
import { getDatabase } from '@/app/lib/notion';
import './globals.css'
import Text from './ui/text';

export default function Home() {
return (
<main className="flex min-h-screen flex-col items-center justify-between p-24">
<div className="z-10 max-w-5xl w-full items-center justify-between font-mono text-sm lg:flex">
<p className="fixed left-0 top-0 flex w-full justify-center border-b border-gray-300 bg-gradient-to-b from-zinc-200 pb-6 pt-8 backdrop-blur-2xl dark:border-neutral-800 dark:bg-zinc-800/30 dark:from-inherit lg:static lg:w-auto lg:rounded-xl lg:border lg:bg-gray-200 lg:p-4 lg:dark:bg-zinc-800/30">
Get started by editing&nbsp;
<code className="font-mono font-bold">app/page.tsx</code>
</p>
<div className="fixed bottom-0 left-0 flex h-48 w-full items-end justify-center bg-gradient-to-t from-white via-white dark:from-black dark:via-black lg:static lg:h-auto lg:w-auto lg:bg-none">
<a
className="pointer-events-none flex place-items-center gap-2 p-8 lg:pointer-events-auto lg:p-0"
href="https://vercel.com?utm_source=create-next-app&utm_medium=appdir-template&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
By{' '}
<Image
src="/vercel.svg"
alt="Vercel Logo"
className="dark:invert"
width={100}
height={24}
priority
/>
</a>
</div>
</div>
// export default function Home() {
// return (
// <main className="flex min-h-screen flex-col items-center justify-between p-24">

<div className="relative flex place-items-center before:absolute before:h-[300px] before:w-[480px] before:-translate-x-1/2 before:rounded-full before:bg-gradient-radial before:from-white before:to-transparent before:blur-2xl before:content-[''] after:absolute after:-z-20 after:h-[180px] after:w-[240px] after:translate-x-1/3 after:bg-gradient-conic after:from-sky-200 after:via-blue-200 after:blur-2xl after:content-[''] before:dark:bg-gradient-to-br before:dark:from-transparent before:dark:to-blue-700 before:dark:opacity-10 after:dark:from-sky-900 after:dark:via-[#0141ff] after:dark:opacity-40 before:lg:h-[360px] z-[-1]">
<Image
className="relative dark:drop-shadow-[0_0_0.3rem_#ffffff70] dark:invert"
src="/next.svg"
alt="Next.js Logo"
width={180}
height={37}
priority
/>
</div>
// </main>
// )
// }

<div className="mb-32 grid text-center lg:max-w-5xl lg:w-full lg:mb-0 lg:grid-cols-4 lg:text-left">
<a
href="https://nextjs.org/docs?utm_source=create-next-app&utm_medium=appdir-template&utm_campaign=create-next-app"
className="group rounded-lg border border-transparent px-5 py-4 transition-colors hover:border-gray-300 hover:bg-gray-100 hover:dark:border-neutral-700 hover:dark:bg-neutral-800/30"
target="_blank"
rel="noopener noreferrer"
>
<h2 className={`mb-3 text-2xl font-semibold`}>
Docs{' '}
<span className="inline-block transition-transform group-hover:translate-x-1 motion-reduce:transform-none">
-&gt;
</span>
</h2>
<p className={`m-0 max-w-[30ch] text-sm opacity-50`}>
Find in-depth information about Next.js features and API.
</p>
</a>
async function getPosts() {
const database = await getDatabase();
return database;
}

<a
href="https://nextjs.org/learn?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
className="group rounded-lg border border-transparent px-5 py-4 transition-colors hover:border-gray-300 hover:bg-gray-100 hover:dark:border-neutral-700 hover:dark:bg-neutral-800/30"
target="_blank"
rel="noopener noreferrer"
>
<h2 className={`mb-3 text-2xl font-semibold`}>
Learn{' '}
<span className="inline-block transition-transform group-hover:translate-x-1 motion-reduce:transform-none">
-&gt;
</span>
</h2>
<p className={`m-0 max-w-[30ch] text-sm opacity-50`}>
Learn about Next.js in an interactive course with&nbsp;quizzes!
</p>
</a>
export default async function Home() {
const posts = await getPosts();
return (
<div>
<main className="flex min-h-screen flex-col items-center justify-between p-24">
<header>
<h1>Next.js blog powered by Notion API</h1>
</header>

<a
href="https://vercel.com/templates?framework=next.js&utm_source=create-next-app&utm_medium=appdir-template&utm_campaign=create-next-app"
className="group rounded-lg border border-transparent px-5 py-4 transition-colors hover:border-gray-300 hover:bg-gray-100 hover:dark:border-neutral-700 hover:dark:bg-neutral-800/30"
target="_blank"
rel="noopener noreferrer"
>
<h2 className={`mb-3 text-2xl font-semibold`}>
Templates{' '}
<span className="inline-block transition-transform group-hover:translate-x-1 motion-reduce:transform-none">
-&gt;
</span>
</h2>
<p className={`m-0 max-w-[30ch] text-sm opacity-50`}>
Explore starter templates for Next.js.
</p>
</a>
<h2>All Posts</h2>
<ol>
{posts.map((post: any) => {
const date = new Date(post.last_edited_time).toLocaleString(
'en-US',
{
month: 'short',
day: '2-digit',
year: 'numeric',
},
);
const slug = post.properties?.Slug?.rich_text[0].plain_text;
return (
<li key={post.id}>
<h3>
<Link href={`/article/${slug}`}>
<Text title={post.properties?.Title?.title} />
</Link>
</h3>

<a
href="https://vercel.com/new?utm_source=create-next-app&utm_medium=appdir-template&utm_campaign=create-next-app"
className="group rounded-lg border border-transparent px-5 py-4 transition-colors hover:border-gray-300 hover:bg-gray-100 hover:dark:border-neutral-700 hover:dark:bg-neutral-800/30"
target="_blank"
rel="noopener noreferrer"
>
<h2 className={`mb-3 text-2xl font-semibold`}>
Deploy{' '}
<span className="inline-block transition-transform group-hover:translate-x-1 motion-reduce:transform-none">
-&gt;
</span>
</h2>
<p className={`m-0 max-w-[30ch] text-sm opacity-50`}>
Instantly deploy your Next.js site to a shareable URL with Vercel.
</p>
</a>
</div>
</main>
)
<p >{date}</p>
<Link href={`/article/${slug}`}>Read post →</Link>
</li>
);
})}
</ol>
</main>
</div>
);
}
Loading

0 comments on commit 1eda3b1

Please sign in to comment.