Skip to content

Instantly share code, notes, and snippets.

@Kyoss79
Created May 29, 2021 10:35
Show Gist options
  • Save Kyoss79/333e431997317a41bc3b95b91c1602bd to your computer and use it in GitHub Desktop.
Save Kyoss79/333e431997317a41bc3b95b91c1602bd to your computer and use it in GitHub Desktop.
Example Typescript implementation of Notion.so API
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