-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
75 lines (55 loc) · 2.02 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import { Client } from "@notionhq/client";
import { NotionToMarkdown } from "notion-to-md";
import { config } from "dotenv";
import fs from "fs/promises";
config();
const notion = new Client({ auth: process.env["NOTION_KEY"] });
const databaseId = process.env["NOTION_DATABASE_ID"];
// set this to whatever directory you want to export markdown files
const MARKDOWN_DIR = "./hugo-site";
export async function downloadMarkdown() {
const n2m = new NotionToMarkdown({
notionClient: notion,
staticFileDir: "hugo-site/static",
});
if (!databaseId)
throw Error("Missing NOTION_DATABASE_ID environment variable.");
// Query the blog database
const res = await notion.databases.query({
database_id: databaseId,
});
console.log("Downloading Pages from Notion....");
await Promise.all(
res.results.map(async (r) => {
const pageData = await notion.pages.retrieve({ page_id: r.id });
// @ts-ignore: JSON data is not typed in pageData
const tags = pageData?.properties?.Tags?.multi_select.map((t) => t.name);
// @ts-ignore: JSON data is not typed in pageData
const author = pageData?.properties?.Authors?.people[0]?.name;
// @ts-ignore: JSON data is not typed in pageData
const title = pageData?.properties?.Name?.title[0]?.plain_text;
if (!title) {
return;
}
// @ts-ignore: JSON data is not typed in pageData
const publishedOn = pageData?.properties["Published On"].date?.start;
const slugifiedTitle =
title?.split(" ").join("-").toLowerCase() ?? "title";
const mdBlocks = await n2m.pageToMarkdown(r.id);
const mdString = n2m.toMarkdownString(mdBlocks);
// Front Matter is in TOML
const hugoHeader = `+++
title = "${title}"
date = "${publishedOn}"
author = "${author ?? "Anonymous"}"
tags = ["${tags.join('", "')}"]
+++`;
await fs.writeFile(
`${MARKDOWN_DIR}/content/${slugifiedTitle || r.id}.md`,
hugoHeader + mdString.parent,
"utf8",
);
}),
);
}
await downloadMarkdown();