makenotion / notion-sdk-js

Official Notion JavaScript Client
https://developers.notion.com/docs
MIT License
4.72k stars 556 forks source link

ORM for Notion Database? #391

Open bitabs opened 1 year ago

bitabs commented 1 year ago

Will we ever have an ORM like Prisma for Notion Database?

janwirth commented 1 year ago

I am having the same problem right now. The types are often not exported, the labels change etc. Some type of code generation would be ideal.

janwirth commented 1 year ago

I wrote this helper function here, where sample is the JSON dump of a page from the SDK imported into typescript. This will infer the field labels and the types. It is also resilient to changing labels as it uses the IDs from the sample page to retrieve props from the actual page.

export const getPropertyUsingLabelToInferId = <T extends {[k: string]: {id: string}}, Label extends keyof T>(sample: T, value: unknown, label: Label): T[Label] => {

    const name_to_id_mappings: Record<keyof T, string> =
        Object.fromEntries(Object.entries(sample as {[k: string]: {id: string}}).map(([k,v]) => ([k, (v).id]))) as Record<keyof T, string>

    const key = name_to_id_mappings[label]
    const fields = Object.values(value as {[k: string]: {id: string}})
    const field = fields.find(field => field.id === key) 
    if (!field) {
      throw Error(`Field ${label.toString()}`)
    }
    return field as unknown as T[Label]
}
schickling commented 1 year ago

👀