Created
May 29, 2021 10:35
-
-
Save Kyoss79/333e431997317a41bc3b95b91c1602bd to your computer and use it in GitHub Desktop.
Example Typescript implementation of Notion.so API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Client } from '@notionhq/client'; | |
import { Block, User } from '@notionhq/client/build/src/api-types'; | |
export type ITodo = { | |
id: string; | |
title: string; | |
assignedTo: User[]; | |
dateCreated: Date; | |
dueDate: Date[]; | |
priority: string; | |
status: string; | |
blocks: Block[]; | |
}; | |
export class NotionClient { | |
client: any; | |
constructor() { | |
if (!process.env.NEXT_PUBLIC_NOTION_TOKEN) { | |
throw new Error('No API TOKEN in .env'); | |
} | |
this.client = new Client({ | |
auth: process.env.NEXT_PUBLIC_NOTION_TOKEN | |
}); | |
} | |
async getPage() { | |
const db = await this.client.databases.query({ | |
database_id: 'YOUR_DATABASE_ID' | |
}); | |
const result = await Promise.all( | |
db.results.map(async (todo: any) => { | |
return await this.transformTodo(todo); | |
}) | |
); | |
return result; | |
} | |
private async transformTodo(todo: any): Promise<ITodo> { | |
// get blocks for this item... | |
const blocks = await this.client.blocks.children.list({ | |
block_id: todo.id.split('-').join('') | |
}); | |
return { | |
id: todo.id, | |
title: todo.properties.Name.title[0].plain_text, | |
assignedTo: todo.properties.Assign.people, | |
dateCreated: todo.properties['Date Created'].created_time, | |
dueDate: todo.properties['Due Date']?.date || null, | |
priority: todo.properties.Priority.select, | |
status: todo.properties.Status?.select.name || null, | |
blocks: blocks.results || null | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment