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 all commits
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
80 changes: 80 additions & 0 deletions lib/markdown.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
const renderNestedListMarkdown = (block:any) => {
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`;
}
};
66 changes: 65 additions & 1 deletion lib/notion.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Client } from "@notionhq/client";

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

Expand All @@ -16,6 +16,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 +75,61 @@ function getRandomInt(min : number, max : number) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}

interface DevToPost {
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 fetch(`https://dev.to/api/articles/${id}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'api-key': `${process.env.DEV_TO_API_KEY}`,
},
body: JSON.stringify({
article: {
title: title,
published: true,
body_markdown: content,
tags: tags,
coverImageUrl: coverImageUrl,
series: 'Notion To Dev To'
},
}),
})
const post = await response.json()
return post
} else {
const response = await fetch(`https://dev.to/api/articles`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'api-key': `${process.env.DEV_TO_API_KEY}`,
},
body: JSON.stringify({
article: {
title: title,
published: true,
body_markdown: content,
tags: tags,
coverImageUrl: coverImageUrl,
series: 'Notion To Dev To'
},
}),
})
const post = await response.json();
return post
}
} catch(err:any){
console.error('Error creating DEV.to blog post:', err.message);
throw new Error('Failed to create DEV.to blog post with code :', err.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.

56 changes: 56 additions & 0 deletions pages/api/post/[pid].ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type { NextApiRequest, NextApiResponse } from 'next'
import { getPage, createDevToBlog, getBlocksPage } from '@/lib/notion'
import { convertToMarkdownNew } from "@/lib/markdown";

export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
if (req.method === 'GET') {
try{
const formattedResponse = [];
const {pid} = req.query;
const linkedPageResponse = await getBlocksPage(pid as string);
const linkedPage = await getPage(pid 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]);
res.status(200).json({message:"Success",post:formattedResponse, details: response_publish});
} catch (error:any) {
res.status(500).json({message:"Error",error});
}
} else if (req.method === 'PUT') {
try {
const formattedResponse = [];
const {pid} = req.query;
const linkedPageResponse = await getBlocksPage(pid as string);
const linkedPage = await getPage(pid 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),
id: req.body?.id
});
const response_publish = createDevToBlog(formattedResponse[0]);
res.status(200).json({message:"Success",post:formattedResponse, details: response_publish});
} catch (error:any) {
res.status(500).json({message:"Error",error});
}
} else {
res.status(405).json({message:"Method not allowed"});
}

res.status(200).json({ name: 'John Doe' })
}
47 changes: 47 additions & 0 deletions pages/blog/[id]/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ 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 notion from "../../../lib/notion";

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

const { href: currentUrl, pathname } = useUrl() ?? {};

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 fetch(apiUrl);

const post = await response.json()

console.log(post);

if(post.status === 200) {
const data = post.data;
await fetch(`${currentUrl}/api/post/${id}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
});
} else {
const details = await fetch(`${currentUrl}/api/post/${id}`);
const FullDetails = await details.json()
const publish_DevTo_Id = await notion.pages.update({
page_id: id,
properties: {
'DevToID' : {
number: parseInt(FullDetails.details.id)
},
}
});
}
} catch(error:any) {
console.error('Some unexpected error occured: ', error.message);
throw new Error('Failed to create blog post with code: ', error.response.status);
}
}

return {
props: {
page,
Expand Down