Skip to content

Commit 2c29a23

Browse files
author
Sergei Orlov
committed
♻️ Move supporting code to src
1 parent c3556b0 commit 2c29a23

File tree

4 files changed

+69
-1
lines changed

4 files changed

+69
-1
lines changed

gatsby-node.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
const { getPages } = require("./notion")
1+
const { getPages } = require("./src/notion-api/get-pages")
22

33
const NODE_TYPE = "Notion"
44

src/error-message.js

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
exports.errorMessage = `gatsby-source-notion-api
2+
3+
Could not fetch data from Notion API. Check if "databaseId" and "token" are provided correctly. Make sure the integration using provided token has access to provided database.`

src/notion-api/get-blocks.js

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
const fetch = require("node-fetch")
2+
const { errorMessage } = require("../error-message")
3+
4+
exports.getBlocks = async ({ page, notionVersion, token }, reporter) => {
5+
let hasMore = true
6+
let pageContent = []
7+
let startCursor = ""
8+
9+
while (hasMore) {
10+
let url = `https://api.notion.com/v1/blocks/${page.id}/children`
11+
12+
if (startCursor) {
13+
url += `?start_cursor=${startCursor}`
14+
}
15+
16+
try {
17+
await fetch(url, {
18+
headers: {
19+
"Content-Type": "application/json",
20+
"Notion-Version": notionVersion,
21+
"Authorization": `Bearer ${token}`,
22+
},
23+
})
24+
.then((res) => res.json())
25+
.then((res) => {
26+
pageContent = pageContent.concat(res.results)
27+
startCursor = res.next_cursor
28+
hasMore = res.has_more
29+
})
30+
} catch (e) {
31+
reporter.panic(errorMessage)
32+
}
33+
}
34+
35+
page.page_content = pageContent
36+
37+
return page
38+
}

src/notion-api/get-pages.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
const fetch = require("node-fetch")
2+
const { errorMessage } = require("../error-message")
3+
const { getBlocks } = require("./get-blocks")
4+
5+
exports.getPages = async ({ token, databaseId, notionVersion = "2021-05-13" }, reporter) => {
6+
try {
7+
const db = await fetch(`https://api.notion.com/v1/databases/${databaseId}/query`, {
8+
method: "POST",
9+
body: JSON.stringify({
10+
page_size: 100,
11+
}),
12+
headers: {
13+
"Content-Type": "application/json",
14+
"Notion-Version": notionVersion,
15+
"Authorization": `Bearer ${token}`,
16+
},
17+
}).then((res) => res.json())
18+
19+
for (let page of db.results) {
20+
page = await getBlocks({ page, token, notionVersion }, reporter)
21+
}
22+
23+
return db.results
24+
} catch (e) {
25+
reporter.panic(errorMessage)
26+
}
27+
}

0 commit comments

Comments
 (0)