Skip to content

Commit 63d3e50

Browse files
authored
merge: pull request #224 from texonom/codex/add-get-backlink-to-notion-api
Add page backlink helper method
2 parents bc882cd + d0ef154 commit 63d3e50

File tree

3 files changed

+36
-0
lines changed

3 files changed

+36
-0
lines changed

packages/nclient/readme.md

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,19 @@ const collectionViewId = 'ab639a5a-853e-45e1-9ef7-133b486c0acf'
2929
const collectionData = await api.getCollectionData(collectionId, collectionViewId)
3030
```
3131

32+
### Fetch backlinks
33+
34+
Backlinks require an auth token.
35+
36+
```ts
37+
const backlinks = await api.getBacklinks({
38+
block: { id: 'page-id', spaceId: 'space-id' }
39+
})
40+
41+
// or simply pass the page id
42+
const pageBacklinks = await api.getPageBacklinks('page-id')
43+
```
44+
3245
### Fetch a database's content
3346

3447
You can pass a database ID to the `getPage` method. The response is an object which contains several important properties:

packages/nclient/src/notion-api.test.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,12 @@ test(`Backlink`, { timeout: 10000, concurrent: true }, async () => {
5959
expect(backlinks.backlinks.length > 0)
6060
})
6161

62+
test(`Page Backlink`, { timeout: 10000, concurrent: true }, async () => {
63+
const api = new NotionAPI({ authToken: process.env.NOTION_TOKEN })
64+
const backlinks = await api.getPageBacklinks('441d5ce2-b781-46d0-9354-54042b4f06d9')
65+
expect(backlinks.backlinks.length > 0)
66+
})
67+
6268
test(`Get block`, { timeout: 10000, concurrent: true }, async () => {
6369
const id = '3f9e0d86-c643-4672-aa0c-78d63fa80598'
6470
const api = new NotionAPI()

packages/nclient/src/notion-api.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -574,6 +574,23 @@ export class NotionAPI {
574574
})
575575
}
576576

577+
/**
578+
* Fetch backlinks for a page by automatically resolving its space id.
579+
* Requires an authToken since backlinks are a private API.
580+
*
581+
* @param pageId page id or url
582+
* @param fetchOption additional fetch options
583+
*/
584+
public async getPageBacklinks(pageId: string, fetchOption?: FetchOption) {
585+
const id = parsePageId(pageId)
586+
const res = await this.getBlocks([id], fetchOption)
587+
const block = res.recordMap.block[id]?.value
588+
if (!block) throw new Error(`Block not found "${uuidToId(id)}"`)
589+
const spaceId = block.space_id
590+
591+
return this.getBacklinks({ block: { id, spaceId } }, fetchOption)
592+
}
593+
577594
public async fetch<T>({
578595
endpoint,
579596
body,

0 commit comments

Comments
 (0)