Skip to content

Instantly share code, notes, and snippets.

@afk-mario
Last active May 24, 2021 15:44
Show Gist options
  • Save afk-mario/33b08d6ca75fea0917231cbf3acbb48a to your computer and use it in GitHub Desktop.
Save afk-mario/33b08d6ca75fea0917231cbf3acbb48a to your computer and use it in GitHub Desktop.
Notion rich text block to markdown
const MY_HOST = 'myhost.com';
export function richTextToMarkdown(block) {
const { type } = block;
if (type !== 'rich_text') {
console.error(
new Error('Triying to convert non rich text block to markdown')
);
return null;
}
return block.rich_text.reduce((acc, curr) => {
const { plain_text: text, annotations, href } = curr;
const { bold, code, italic, strikethrough } = annotations;
const url = href && new URL(href);
let path = href;
if (url?.hostname === MY_HOST) {
path = url.pathname;
}
let parsed = text;
if (italic) {
parsed = `_${parsed}_`;
}
if (bold) {
parsed = `**${parsed}**`;
}
if (code) {
parsed = `\`${parsed}\``;
}
if (strikethrough) {
parsed = `~~${parsed}~~`;
}
if (path) {
parsed = `[${parsed}](${path})`;
}
return `${acc}${parsed}`;
}, '');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment