Skip to content

Commit 98fd09e

Browse files
author
Sergei Orlov
committed
✨ Add support for recursive DB fetching
Should work for cases when a database has over 100 rows Closes #4
1 parent e852355 commit 98fd09e

File tree

1 file changed

+37
-18
lines changed

1 file changed

+37
-18
lines changed

src/notion-api/get-pages.js

+37-18
Original file line numberDiff line numberDiff line change
@@ -3,25 +3,44 @@ const { errorMessage } = require("../error-message")
33
const { getBlocks } = require("./get-blocks")
44

55
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.children = await getBlocks({ id: page.id, token, notionVersion }, reporter)
6+
let hasMore = true
7+
let startCursor = ""
8+
const url = `https://api.notion.com/v1/databases/${databaseId}/query`
9+
const body = {
10+
page_size: 100,
11+
}
12+
13+
const pages = []
14+
15+
while (hasMore) {
16+
if (startCursor) {
17+
body.start_cursor = startCursor
18+
}
19+
20+
try {
21+
const result = await fetch(url, {
22+
method: "POST",
23+
body: JSON.stringify(body),
24+
headers: {
25+
"Content-Type": "application/json",
26+
"Notion-Version": notionVersion,
27+
Authorization: `Bearer ${token}`,
28+
},
29+
}).then((res) => res.json())
30+
console.log(result.next_cursor, result.results.length)
31+
32+
startCursor = result.next_cursor
33+
hasMore = result.has_more
34+
35+
for (let page of result.results) {
36+
page.children = await getBlocks({ id: page.id, token, notionVersion }, reporter)
37+
38+
pages.push(page)
39+
}
40+
} catch (e) {
41+
reporter.panic(errorMessage)
2142
}
2243

23-
return db.results
24-
} catch (e) {
25-
reporter.panic(errorMessage)
44+
return pages
2645
}
2746
}

0 commit comments

Comments
 (0)