What is Model?
A Model in Alapa represents a class that maps to a database table (or a MongoDB collection, if you're using MongoDB).
To define a model, create a class and decorate it with @TableModel()
:
src/app/models/user.ts
import { Model, PrimaryColumn, Column } from "alapa";
@TableModel()
export class Users extends Model {
@PrimaryColumn()
id: number;
@Column()
firstName: string;
@Column()
lastName: string;
@Column()
isActive: boolean;
}
This generates the following database table:
untitled
+-------------+---------------+----------------------------+
| users |
+-------------+---------------+----------------------------+
| id | int(11) | PRIMARY KEY AUTO_INCREMENT |
| first_name | varchar(255) | NOT NULL |
| last_name | varchar(255) | NOT NULL |
| is_active | boolean | DEFAULT false |
+-------------+---------------+----------------------------+
Every model must have a primary column (
@PrimaryColumn
) or anObjectId
(when using MongoDB).
Saving a New Record
You can create and save a new user like this:
untitled
const user = new Users();
user.firstName = "John";
user.lastName = "Doe";
user.isActive = true;
await user.save();
console.log(`New User (${user.firstName}) saved successfully.`);
Retrieving Data
Fetch all users
untitled
const users = await Users.find();
if (empty(users)) {
console.log("Users table is empty");
} else {
console.log(`Users fetched successfully:`, users);
}
Fetch a specific user by ID
src/app/index.ts
const user = await Users.findOneBy({ id: 1 });
if (!user) {
console.log("User not found");
} else {
console.log(`User (${user.firstName}) fetched successfully`);
}
note
Alapa Model is built on top of TypeORM. This documentation focuses primarily on the customizations, new features, and core concepts specific to working with databases in the Alapa project.
For a deeper understanding of how the underlying model works, refer to the official TypeORM documentation.