Creating a Model

Creating a User Model

To create the simplest User class, you should first define the Users model. Here is an example code to create such a model:

import {
    Boolean,
    Column,
    PrimaryGeneratedColumn,
    String,
    Table
} from "@myroslavshymon/orm";

@Table({name: 'users'})
export class Users {
    @PrimaryGeneratedColumn({type: 'BIGINT'})
    user_id: number;

    @String({type: "VARCHAR", length: 255})
    @Column({options: {unique: true, nullable: false}})
    username: string;

    @String({type: "VARCHAR", length: 255})
    @Column({options: {nullable: false}})
    email: string;

    @String({type: "VARCHAR", length: 255})
    @Column({options: {nullable: false}})
    password: string;

    @Column({options: {dataType: 'BOOLEAN', defaultValue: false}})
    is_active: boolean;
}

Пояснення:

  • @Table({name: 'users'}): Specifies that this model will be stored in a named tableusers.

  • @PrimaryGeneratedColumn({type: 'BIGINT'}): Declares a field user_id as the primary key of the type BIGINT, which is automatically generated.

  • @String({type: "VARCHAR", length: 255}): Defines a field username as a string up to 255 characters long, with unique values ​​and mandatory.

  • @Column({options: {nullable: false}}): Indicates that fields email and password are requeired.

  • @Column({options: {dataType: 'BOOLEAN', defaultValue: false}}): Declares a field is_active as a boolean with a default value false.

Додавання Моделі до Системи

After creating the model, you need to add it to the database configuration in your ORM system. This is done by including the model in the models array when initializing the database manager:

import { DatabaseManager, DatabasesTypes, DataSourceContext } from "@myroslavshymon/orm";
import { Users } from "./models/users"; // шлях до моделі

export const databaseManager = new DatabaseManager<DatabasesTypes.POSTGRES>(
    {
        type: DatabasesTypes.POSTGRES,
        host: 'localhost',
        user: 'postgres',
        password: 'xxx',
        port: 5432,
        database: 'first',
        models: [
            Users
        ],
    },
    new DataSourceContext()
);

Creating a Table in the Database

To create the users table in the database, follow these steps:

  1. Initialize the database connection using createOrmConnection().

  2. Run npm run start to synchronize the Users class and map it in current_database_ingot in the migrations table for subsequent migration creation.

Last updated