μ°Έκ³ ν λ§ : https://jamstackthemes.dev/theme/notion-blog-nextjs-coral/
yarn add @notionhq/client
lib
μ pages/api
μ€ μ΄λ λλ ν 리λ₯Ό μ¬μ©ν΄μΌν κΉlib
β ν΄λΌμ΄μΈνΈ μΈ‘μ λμμ΄ λλ μ νΈλ¦¬ν° κΈ°λ₯μ©pages/api
β μλ² μΈ‘μ API μλν¬μΈνΈ μ©λhas_child
μμ±μ μ΄μ©νμ¬, λͺ¨λ λ
Έλλ₯Ό νμνκ² νλ€λ©΄ κ°λ₯νμ§ μμκΉimport { Client } from "@notionhq/client";
const notion = new Client({
auth: process.env.NOTION_TOKEN,
});
export const getBlocks = async (blockId) => {
blockId = blockId.replaceAll("-", "");
// μλ‘μ΄ newObj μ blockId μ ν΄λΉνλ λΈλμ μ λΆ μΆκ°νλ€.
// λ무 λ§μ λ°μ΄ν°λ‘ μΈν΄ κ³ΌλΆνλ₯Ό λ°©μ§νκΈ°μν΄ depth 2 κΉμ§λ§ λ½μλΈλ€.
async function flattenBlocks(blockId, depth = 0) {
const blockData = await notion.blocks.children.list({ block_id: blockId });
const newObj = [];
for (let block of blockData.results) {
newObj.push({ ...block, depth });
if (depth < 2 && block.has_children) {
const childBlockData = await notion.blocks.children.list({ block_id: block.id });
for (let childBlock of childBlockData.results) {
newObj.push({ ...childBlock, depth: depth + 1 });
if (childBlock.has_children) {
// λ€μ¬μ°κΈ°λ₯Ό μκΈ°μν΄ μΆκ°
const grandChildren = await flattenBlocks(childBlock.id, depth + 1);
newObj.push(...grandChildren);
}
}
}
}
return newObj;
}
const flattenedBlocks = await flattenBlocks(blockId);
return flattenedBlocks;
};
μ΄ν, κ° λΈλμ ν΄λΉνλ νμμΌλ‘ μΆλ ₯νλ€.const renderBlock = (block) => {
// κ° λΈλμ μμλ‘ type(typeμ λ°λ₯Έ returnμ μν΄)
// id (μ λν¬ν keyκ°μ μ μ©ν λ λ±λ±..)
// depth (λ€μ¬μ°κΈ°κ° λ κ²½μ°, λμ΄μ°κΈ°λ₯Ό ν΄μ£Όλ €κ³ )
const { type, id, depth } = block;
const value = block[type];
// λμ΄μ°κΈ° μ€νμΌμ μλ¨νκ·Έμ μΆκ°
const indentStyle = { paddingLeft: `${depth * 10}px` };
switch (type) {
case "paragraph":
return (
<p style={indentStyle}>
<Text text={value.rich_text} />
</p>
);
case "heading_1":
return (
<h1 style={indentStyle}>
<Text text={value.rich_text} />
</h1>
);
...
π’Β μ²μμ νμλ, μ΄λ €μ΄μ