فهرست منبع

fix: handle Notion API block nesting change and null date/image edge cases

- Normalize recordMap to unwrap new nested block structure from Notion API
- Guard null createdAt and imageUrl in blog list and post page
- Fix tailwind config to use @heroui/theme instead of @nextui-org/theme
- Filter getAllBlogPosts to only include page-type blocks with titles

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
rriecc 7 ماه پیش
والد
کامیت
348d382d05
7فایلهای تغییر یافته به همراه97 افزوده شده و 50 حذف شده
  1. 12 4
      app/blog/[blogId]/page.tsx
  2. 3 1
      app/blog/page.tsx
  3. 17 13
      components/blog-list.tsx
  4. 14 12
      components/notion-page.tsx
  5. 46 15
      lib/notion.ts
  6. 3 3
      tailwind.config.js
  7. 2 2
      types/blog.ts

+ 12 - 4
app/blog/[blogId]/page.tsx

@@ -41,8 +41,12 @@ export async function generateMetadata({
       type: "article",
       url: `/blog/${blogId}`,
       authors: [siteConfig.author],
-      publishedTime: new Date(block?.created_time).toISOString(),
-      modifiedTime: new Date(block?.last_edited_time).toISOString(),
+      ...(block?.created_time && {
+        publishedTime: new Date(block.created_time).toISOString(),
+      }),
+      ...(block?.last_edited_time && {
+        modifiedTime: new Date(block.last_edited_time).toISOString(),
+      }),
       images: ogImages,
     },
     twitter: {
@@ -73,8 +77,12 @@ export default async function Page({
     "@type": "Article",
     headline: title,
     description,
-    datePublished: new Date(block?.created_time).toISOString(),
-    dateModified: new Date(block?.last_edited_time).toISOString(),
+    ...(block?.created_time && {
+      datePublished: new Date(block.created_time).toISOString(),
+    }),
+    ...(block?.last_edited_time && {
+      dateModified: new Date(block.last_edited_time).toISOString(),
+    }),
     ...(coverUrl && {
       image: customMapImageUrl(coverUrl, block),
     }),

+ 3 - 1
app/blog/page.tsx

@@ -27,7 +27,9 @@ export default async function Page() {
 
   const postsWithImages = blogPosts.map((post) => ({
     ...post,
-    imageUrl: customMapImageUrl(post.pageCover, post.block),
+    imageUrl: post.pageCover
+      ? customMapImageUrl(post.pageCover, post.block)
+      : undefined,
   }));
 
   return <BlogList blogPosts={postsWithImages} />;

+ 17 - 13
components/blog-list.tsx

@@ -32,21 +32,25 @@ export function BlogList({ blogPosts }: BlogListProps) {
         {blogPosts.map(({ id, title, imageUrl, createdAt }) => (
           <Link key={id} href={`/blog/${id}`}>
             <Card className="dark:bg-darkBg dark:border-2 dark:border-knight rounded-[2rem]">
-              <CardBody className="p-0">
-                <Image
-                  alt={title}
-                  className="w-full rounded-b-none object-cover h-[200px]"
-                  height={200}
-                  sizes="(max-width: 768px) 100vw, (max-width: 1024px) 50vw, 33vw"
-                  src={imageUrl}
-                  width={400}
-                />
-              </CardBody>
+              {imageUrl && (
+                <CardBody className="p-0">
+                  <Image
+                    alt={title}
+                    className="w-full rounded-b-none object-cover h-[200px]"
+                    height={200}
+                    sizes="(max-width: 768px) 100vw, (max-width: 1024px) 50vw, 33vw"
+                    src={imageUrl}
+                    width={400}
+                  />
+                </CardBody>
+              )}
               <CardFooter className="flex justify-between">
                 <h2 className="font-[500] text-lg">{title}</h2>
-                <time className="text-sm" dateTime={createdAt.toISOString()}>
-                  {createdAt.toDateString()}
-                </time>
+                {createdAt && (
+                  <time className="text-sm" dateTime={createdAt.toISOString()}>
+                    {createdAt.toDateString()}
+                  </time>
+                )}
               </CardFooter>
             </Card>
           </Link>

+ 14 - 12
components/notion-page.tsx

@@ -127,18 +127,20 @@ export const NotionPage = ({
         <h1 className="my-4 text-center text-xl font-bold md:text-2xl">
           {title}
         </h1>
-        <div className="ml-[15px] md:mx-[296px] mb-4">
-          <time
-            className="w-fit dark:border-knight dark:bg-transparent dark:border-2 bg-[#ece7e7] border-0 py-1 px-4 rounded-full inline-block"
-            dateTime={new Date(
-              recordMap.block[rootPageId].value?.created_time,
-            ).toISOString()}
-          >
-            {new Date(
-              recordMap.block[rootPageId].value?.created_time,
-            ).toDateString()}
-          </time>
-        </div>
+        {recordMap.block[rootPageId]?.value?.created_time && (
+          <div className="ml-[15px] md:mx-[296px] mb-4">
+            <time
+              className="w-fit dark:border-knight dark:bg-transparent dark:border-2 bg-[#ece7e7] border-0 py-1 px-4 rounded-full inline-block"
+              dateTime={new Date(
+                recordMap.block[rootPageId].value.created_time,
+              ).toISOString()}
+            >
+              {new Date(
+                recordMap.block[rootPageId].value.created_time,
+              ).toDateString()}
+            </time>
+          </div>
+        )}
 
         <NotionRenderer
           components={components}

+ 46 - 15
lib/notion.ts

@@ -9,8 +9,30 @@ import { notionBlogConfig } from "@/config/site";
 
 const notion = new NotionAPI();
 
+// The Notion API now wraps block entries in an extra layer:
+//   block[id] = { spaceId, value: { value: Block, role } }
+// react-notion-x expects the older shape:
+//   block[id] = { value: Block, role }
+// This type covers both shapes so we can unwrap safely.
+type NestedBlockEntry = {
+  spaceId?: string;
+  value: { value: Block; role: string };
+};
+
+function normalizeRecordMap(recordMap: ExtendedRecordMap): ExtendedRecordMap {
+  const block = { ...recordMap.block };
+  for (const [id, entry] of Object.entries(block)) {
+    const nested = entry as unknown as NestedBlockEntry;
+    if (nested?.value?.value !== undefined && nested?.value?.role !== undefined) {
+      block[id] = nested.value;
+    }
+  }
+  return { ...recordMap, block };
+}
+
 export const getPageContent = cache(async (pageId: string) => {
-  const recordMap = await notion.getPage(pageId);
+  const raw = await notion.getPage(pageId);
+  const recordMap = normalizeRecordMap(raw);
   const title = getPageTitle(recordMap);
   const blocks = recordMap.block;
 
@@ -18,27 +40,36 @@ export const getPageContent = cache(async (pageId: string) => {
 });
 
 export async function getAllBlogPosts(pageId: string) {
-  const recordMap = await notion.getPage(pageId);
+  const recordMap = normalizeRecordMap(await notion.getPage(pageId));
   const blocks = recordMap.block;
 
   let blogPosts: Blog[] = [];
 
-  Object.entries(blocks).map(([key, value]) => {
-    if (key !== notionBlogConfig.blogParentId) {
-      blogPosts.push({
-        id: key,
-        block: value.value,
-        pageCover: value.value.format?.page_cover,
-        title: value.value.properties?.title[0][0],
-        createdAt: new Date(value.value.created_time),
-        lastEditedAt: new Date(value.value.last_edited_time),
-        description: value.value.properties?.["\\u2O5F"]?.[0]?.[0] ?? "",
-      });
+  Object.entries(blocks).forEach(([key, value]) => {
+    const block = value.value;
+    if (
+      key === notionBlogConfig.blogParentId ||
+      block?.type !== "page" ||
+      !block?.properties?.title
+    ) {
+      return;
     }
+    blogPosts.push({
+      id: key,
+      block,
+      pageCover: block.format?.page_cover,
+      title: block.properties.title[0][0],
+      createdAt: block.created_time ? new Date(block.created_time) : null,
+      lastEditedAt: block.last_edited_time
+        ? new Date(block.last_edited_time)
+        : null,
+      description: block.properties?.["\\u2O5F"]?.[0]?.[0] ?? "",
+    });
   });
 
-  // Sort by newest first
-  blogPosts.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
+  blogPosts.sort(
+    (a, b) => (b.createdAt?.getTime() ?? 0) - (a.createdAt?.getTime() ?? 0),
+  );
 
   return blogPosts;
 }

+ 3 - 3
tailwind.config.js

@@ -1,11 +1,11 @@
-import { nextui } from "@nextui-org/theme";
+import { heroui } from "@heroui/theme";
 
 /** @type {import('tailwindcss').Config} */
 module.exports = {
   content: [
     "./components/**/*.{js,ts,jsx,tsx,mdx}",
     "./app/**/*.{js,ts,jsx,tsx,mdx}",
-    "./node_modules/@nextui-org/theme/dist/**/*.{js,ts,jsx,tsx}",
+    "./node_modules/@heroui/theme/dist/**/*.{js,ts,jsx,tsx}",
   ],
   theme: {
     extend: {
@@ -33,5 +33,5 @@ module.exports = {
     },
   },
   darkMode: "class",
-  plugins: [nextui(), require("tailwind-scrollbar-hide")],
+  plugins: [heroui(), require("tailwind-scrollbar-hide")],
 };

+ 2 - 2
types/blog.ts

@@ -5,7 +5,7 @@ export type Blog = {
   title: string;
   block: Block;
   pageCover: string;
-  createdAt: Date;
-  lastEditedAt: Date;
+  createdAt: Date | null;
+  lastEditedAt: Date | null;
   description: string;
 };