I am trying to retrieve all blocks from Notion page including children blocks of blocks.
In order to do this first I created function getPageAllBlocks
which takes all blocks from page without children blocks. getPageAllBlocks
function is tested and works good.
Next function that I want is fn which takes Notion pageId and gets all blocks including children blocks of blocks. It looks like:
const getPageAllBlocksWithChildren = async (pageId, searchedSize = 100) => {
const pageBlocks = await getPageAllBlocks(pageId, searchedSize)
let childrenBlocks = []
await pageBlocks.forEach(async (block) => {
if (block.has_children !== true) return
const result = await getPageAllBlocksWithChildren(block.id, searchedSize)
childrenBlocks = [...childrenBlocks, ...result]
})
return [...pageBlocks, ...childrenBlocks]
}
It is using getPageAllBlocks
to get all blocks from page and next it iterates through them. For blocks that has children, I invoke the same function. I'm not sure, but I think that it is a good idea because children blocks in Notion can be nested endlessly.
And the result – function always returns only first level pageBlocks not a single one from children blocks. Through debugging, I see that the result in array forEach function is obtained correctly. But in some way it doesn't is included in final result.
It doesn't even work for tests with one nested level. I work on Node.js v18.1.0.
I have a feeling that I am making some simple mistake. If someone sees it, please indicate it.
I tried:
- change async/await syntax to promises
- refactor fn in a more recursive mode (passing
pageBlocks
,has_more
ingetPageAllBlocksWithChildren
)