Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Added the functionality for devTo automation but getting Type Error #12

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions app/api/devToBlogs/[id]/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { getBlocks, getPage, createDevToBlog, getBlocksPage } from "@/lib/notion";
ighoshsubho marked this conversation as resolved.
Show resolved Hide resolved
import { convertToMarkdownNew } from "@/lib/notion";
import { NextResponse } from "next/server";

export const GET = async (req: Request, res: Response) => {
try{
const formattedResponse = [];
const linkedPageId = req.url.split('devToBlogs/')[1];
const linkedPageResponse = await getBlocksPage(linkedPageId as string);
const linkedPage = await getPage(linkedPageId as string);
const contentMarkdown = linkedPageResponse.results.map((block: any) => {
convertToMarkdownNew(block).join("\n");
});
formattedResponse.push({
title: linkedPage.properties.Name.title[0].plain_text,
content: contentMarkdown,
coverImageUrl: linkedPage.cover.external.url,
tags: linkedPage.properties['Tags'].multi_select.map((tag : any) => tag.name)
});
const response_publish = createDevToBlog(formattedResponse[0]);
return NextResponse.json({message:"Success",post:formattedResponse, details: response_publish},{status:200});
} catch (error:any) {
NextResponse.json({message:"Error",error},{status:500});
}
}

export const PUT = async (req: Request, res: Response) => {
try{
const formattedResponse = [];
const linkedPageId = req.url.split('devToBlogs/')[1];
const linkedPageResponse = await getBlocksPage(linkedPageId as string);
const linkedPage = await getPage(linkedPageId as string);
const contentMarkdown = linkedPageResponse.results.map((block: any) => {
convertToMarkdownNew(block).join("\n");
});
const {id} = await res.json();
formattedResponse.push({
title: linkedPage.properties.Name.title[0].plain_text,
content: contentMarkdown,
coverImageUrl: linkedPage.cover.external.url,
tags: linkedPage.properties['Tags'].multi_select.map((tag : any) => tag.name),
id: id
});
const response_publish = createDevToBlog(formattedResponse[0]);
return NextResponse.json({message:"Success",post:formattedResponse, details: response_publish},{status:200});
} catch (error:any) {
NextResponse.json({message:"Error",error},{status:500});
}
}
155 changes: 153 additions & 2 deletions lib/notion.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Client } from "@notionhq/client";
import axios from "axios";

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

Expand All @@ -16,6 +17,13 @@ export const getPage = async (pageId : string) => {
return response;
};

export const getBlocksPage = async (linkedPageId: string) => {
const response = await notion.blocks.children.list({
block_id: linkedPageId,
});
return response;
}

export const getBlocks = async (blockId : string) => {
blockId = blockId.replaceAll("-", "");

Expand Down Expand Up @@ -68,4 +76,147 @@ function getRandomInt(min : number, max : number) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
}

const renderNestedListMarkdown = (block:any) => {
ighoshsubho marked this conversation as resolved.
Show resolved Hide resolved
const { type } = block;
const value = block[type];

if (!value) return "";

const isNumberedList = value.children?.type === "numbered_list_item";
const listType = isNumberedList ? "ol" : "ul";

return value.children?.map((child:any) => {
const listItemText = child.numbered_list_item || child.bulleted_list_item;
if (listItemText) {
return ` - ${convertToMarkdown(listItemText.rich_text)}\n${convertToMarkdownNew(child)}`;
}
return "";
})
.join("");
};

function convertToMarkdown(richText:any) {
return richText.map((textObj:any) => textObj.text.content).join('');
}

export const convertToMarkdownNew = (block:any) => {
const { type } = block;
const value = block[type];

switch (type) {
case "paragraph":
return `${convertToMarkdown(value.rich_text)}\n\n`;
case "heading_1":
return `# ${convertToMarkdown(value.rich_text)}\n\n`;
case "heading_2":
return `## ${convertToMarkdown(value.rich_text)}\n\n`;
case "heading_3":
return `### ${convertToMarkdown(value.rich_text)}\n\n`;
case "bulleted_list":
case "numbered_list":
return value.children?.map((child:any) => convertToMarkdownNew(child))
.join("");
case "bulleted_list_item":
case "numbered_list_item":
return `- ${convertToMarkdown(value.rich_text)}\n${renderNestedListMarkdown(block)}`;
case "to_do":
return `- [${value.checked ? "x" : " "}] ${convertToMarkdown(value.rich_text)}\n`;
case "toggle":
return `**${convertToMarkdown(value.rich_text)}**\n${block.children?.map((child:any) => convertToMarkdownNew(child))
.join("")}`;
case "child_page":
return `**${value.title}**\n${block.children?.map((child:any) => convertToMarkdownNew(child))
.join("")}`;
case "image":
const src = value.type === "external" ? value.external.url : value.file.url;
const caption = value.caption ? value.caption[0]?.plain_text : "";
return `![${caption}](${src})\n\n`;
case "divider":
return "---\n\n";
case "quote":
return `> ${convertToMarkdown(value.rich_text)}\n\n`;
case "code":
return `\`\`\`${value.language}\n` + convertToMarkdown(value.rich_text) + "\n```\n\n";
case "file":
const srcFile = value.type === "external" ? value.external.url : value.file.url;
const captionFile = value.caption ? value.caption[0]?.plain_text : "";
return `[${captionFile}](${srcFile})\n\n`;
case "bookmark":
return `[${value.url}](${value.url})\n\n`;
case "table":
return value.children?.map((child:any) => convertToMarkdownNew(child))
.join("");
case "column_list":
return block.children?.map((child:any) => convertToMarkdownNew(child))
.join("");
case "column":
return block.children?.map((child:any) => convertToMarkdownNew(child))
.join("");
default:
return `❌ Unsupported block (${type === "unsupported" ? "unsupported by Notion API" : type})\n\n`;
}
};

type DevToPost = {
ighoshsubho marked this conversation as resolved.
Show resolved Hide resolved
title: string;
content: string;
tags: string;
coverImageUrl: string;
id?: string;
};


export const createDevToBlog = async ({title, content, tags, coverImageUrl,id}:DevToPost) => {
try {

if(id){
const response = await axios.put(
`https://dev.to/api/articles/${id}`,
{
article: {
title: title,
published: true,
body_markdown: content,
tags: tags,
coverImageUrl: coverImageUrl,
series: 'Notion To Dev To'
},
},
{
headers: {
'Content-Type': 'application/json',
'api-key': process.env.DEV_TO_API_KEY,
},
}
);
return response.data;
} else {
const response = await axios.post(
'https://dev.to/api/articles',
{
article: {
title: title,
published: true,
body_markdown: content,
tags: tags,
coverImageUrl: coverImageUrl,
series: 'Notion To Dev To'
},
},
{
headers: {
'Content-Type': 'application/json',
'api-key': process.env.DEV_TO_API_KEY,
},
}
);
return response.data;
}
} catch (error:any) {
console.error('Error creating DEV.to blog post:', error.message);
throw new Error('Failed to create DEV.to blog post with code :', error.response.status);
}

};
48 changes: 48 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"@types/react": "18.2.15",
"@types/react-dom": "18.2.7",
"autoprefixer": "10.4.14",
"axios": "^1.4.0",
ighoshsubho marked this conversation as resolved.
Show resolved Hide resolved
"eslint": "8.45.0",
"eslint-config-next": "13.4.12",
"next": "13.4.12",
Expand Down
44 changes: 44 additions & 0 deletions pages/blog/[id]/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { oneDark } from 'react-syntax-highlighter/dist/cjs/styles/prism'
import { CopyToClipboard } from 'react-copy-to-clipboard';
import Code from "@/components/Code";
import axios from "axios";
import notion from "../../../lib/notion";

const renderNestedList = (block: { [x: string]: any; type?: any; }) => {
const { type } = block;
Expand Down Expand Up @@ -252,6 +254,48 @@ export const getStaticProps: GetStaticProps = async (context: any) => {
const page = await getPage(id);
const blocks = await getBlocks(id);

if(page.properties.DevToPublish.checkbox === true) {

try{
const ID:number = page.properties.DevToId.number;

console.log(`${ID?ID:id}`);

const apiUrl = `https://dev.to/api/articles/${ID?ID:id}`;

console.log(apiUrl);

const response = await axios.get(apiUrl);

console.log(response);

if(response.status === 200) {
const data = response.data;
await axios.put(`${process.env.YOUR_SITE_URL}/${id}`, {...data}
ighoshsubho marked this conversation as resolved.
Show resolved Hide resolved
);
} else {
const details = await axios.get(`${process.env.YOUR_SITE_URL}/${id}`);
const publish_DevTo_Id = await notion.pages.update({
page_id: id,
properties: {
'DevToID' : {
number: parseInt(details.details.id)
},
}
});
}
} catch(error) {
ighoshsubho marked this conversation as resolved.
Show resolved Hide resolved
const details = await axios.get(`${process.env.YOUR_SITE_URL}/${id}`);
const publish_DevTo_Id = await notion.pages.update({
page_id: id,
properties: {
'DevToID' : {
number: parseInt(details.details.id)
},
}
});
}
}
return {
props: {
page,
Expand Down