notion-database-parser
v0.0.2
Published
A library to help parse structured data from notion databases
Downloads
8
Readme
Notion Database Parser (WIP)
A schema and parser api for reading Notion Database Objects into custom typed objects.
Install
THIS LIBRARY IS A WORK IN PROGRESS AND IS LIKELY TO UNDERGO MAJOR CHANGES!
npm install --save 'notion-database-parser'
Dependencies
@notionhq/client
: "^2.2.1"
Why
Notion databases have complex data types. Sometimes you want all the detail, but at other times you just want the data from the table as a simple object.
This library gives you the tools to write simple and reusable parsers which can translate notion's database properties into an expected and typed object. It will report errors if the properties do not match the expected structure.
Usage
- Define your database schema (what data do you want)
import { SchemaBuilder, ParserBuilder, isFullUser } from 'notion-database-parser';
const schema = SchemaBuilder.create()
.addProperty('task', 'Task', 'title')
.addProperty('date', 'Date', 'date')
.addProperty('people', 'Person', 'multi_select')
.addProperty('hours', 'Hours', 'number')
.addProperty('rate', 'Rate', 'number')
.addProperty('category', 'Category', 'select')
.build();
- Define your parser (how to translate notion property objects to simple types)
Use the default parsers:
const parser = ParserBuilder.create().build(schema)
Or Add overrides for specific notion property types.
const parser = ParserBuilder.create()
.addParserForType('number', v => v.number || 0)
.addParserForType('people', v => {
return v.people.map(person => (isFullUser(person) ? person.name : ''));
})
.build(schema);
- Parse data returned from notion database queries
const res = await notion.databases.query({
database_id: this.databaseId,
filter: { ... },
});
const data = parser.parseQueryDatabaseResponse(res);
The return type of the parser is inferred from the Schema and return types of the parser functions.
In this example data
will be an array of objects typed:
type Data = {
task: string;
data: Date | null;
people: string[];
hours: number;
rate: number,
category: string | []
}
Type guards
Exposes two helpful type guards.
isFullUser()
- refinesPartialUserObjectResponse
toUserObjectResponse
.isFullDatabaseObject()
- refines result objects fromQueryDatabaseResponse
to full objects.
TODO:
- add tests