diff --git a/packages/nclient/readme.md b/packages/nclient/readme.md index c626ba5f..a05571e9 100644 --- a/packages/nclient/readme.md +++ b/packages/nclient/readme.md @@ -29,6 +29,19 @@ const collectionViewId = 'ab639a5a-853e-45e1-9ef7-133b486c0acf' const collectionData = await api.getCollectionData(collectionId, collectionViewId) ``` +### Fetch backlinks + +Backlinks require an auth token. + +```ts +const backlinks = await api.getBacklinks({ + block: { id: 'page-id', spaceId: 'space-id' } +}) + +// or simply pass the page id +const pageBacklinks = await api.getPageBacklinks('page-id') +``` + ### Fetch a database's content You can pass a database ID to the `getPage` method. The response is an object which contains several important properties: diff --git a/packages/nclient/src/notion-api.test.ts b/packages/nclient/src/notion-api.test.ts index 519feb58..543dfb8b 100644 --- a/packages/nclient/src/notion-api.test.ts +++ b/packages/nclient/src/notion-api.test.ts @@ -59,6 +59,12 @@ test(`Backlink`, { timeout: 10000, concurrent: true }, async () => { expect(backlinks.backlinks.length > 0) }) +test(`Page Backlink`, { timeout: 10000, concurrent: true }, async () => { + const api = new NotionAPI({ authToken: process.env.NOTION_TOKEN }) + const backlinks = await api.getPageBacklinks('441d5ce2-b781-46d0-9354-54042b4f06d9') + expect(backlinks.backlinks.length > 0) +}) + test(`Get block`, { timeout: 10000, concurrent: true }, async () => { const id = '3f9e0d86-c643-4672-aa0c-78d63fa80598' const api = new NotionAPI() diff --git a/packages/nclient/src/notion-api.ts b/packages/nclient/src/notion-api.ts index c7e383ea..b478173f 100644 --- a/packages/nclient/src/notion-api.ts +++ b/packages/nclient/src/notion-api.ts @@ -574,6 +574,23 @@ export class NotionAPI { }) } + /** + * Fetch backlinks for a page by automatically resolving its space id. + * Requires an authToken since backlinks are a private API. + * + * @param pageId page id or url + * @param fetchOption additional fetch options + */ + public async getPageBacklinks(pageId: string, fetchOption?: FetchOption) { + const id = parsePageId(pageId) + const res = await this.getBlocks([id], fetchOption) + const block = res.recordMap.block[id]?.value + if (!block) throw new Error(`Block not found "${uuidToId(id)}"`) + const spaceId = block.space_id + + return this.getBacklinks({ block: { id, spaceId } }, fetchOption) + } + public async fetch({ endpoint, body,