Generate models

Automatically create Typescript classes that mirror your database tables, constraints, and relationships.

Manually creating data classes to represent ideas in your application can be difficult to maintain accurately, particularly when you have an active code base and multiple application layers. Automatically generating models and keeping them consistently in sync helps everyone.

Add script to package

To generate models in your project we can add a script to our package.json file that handles this automatically.

"scripts" {
    "db:models": "sync-database-models PATH=./models API_KEY=your_api_key"
}

In the example above we name the command we'll call to generate these models db:models and we told the project what path, or the location in the project, on where to create and store the model files. Before we can do this though you must provide your API key from Outerbase as it's the remove server platform that does the database introspection with your connected database.

Run the script

With our script in place all we need to do to generate a new Typescript file for each database table we have is by running

npm run db:models

Sample output

After running the script above check the folder path you declared for your models to be saved to. Assuming everything ran successfully then you should see one file for each table in your database. If your database had multiple schemas (e.g. Postgres database) then your model folder will contain folders that map to each schema, with the table classes inside those.

When a table is in the public schema it will be created at the root level of the models folder.

import { BaseTable, Column } from '@outerbase/sdk';

export class Users extends BaseTable {
    @Column({ name: "id", primary: true })
    id: string;

    @Column({ name: "email", nullable: false })
    email: string;

    @Column({ name: "password", nullable: true })
    password?: string;

    
    constructor(data: any) {
        super({
            _name: "users",
            _schema: "public"
        });

        this.id = data.id;
        this.email = data.email;
        this.password = data.password;
    }
}

Last updated