notion-sdk-js icon indicating copy to clipboard operation
notion-sdk-js copied to clipboard

ORM for Notion Database?

Open bitabs opened this issue 2 years ago • 3 comments

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

bitabs avatar Mar 08 '23 14:03 bitabs

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 avatar Mar 17 '23 16:03 janwirth

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]
}

janwirth avatar Mar 17 '23 16:03 janwirth

👀

schickling avatar May 02 '23 16:05 schickling