Models & Decorators

Learn how to define models using decorators and leverage the powerful BaseModel class.

The @Entity Decorator

The @Entity decorator defines the database table for your model:

1import { Entity, BaseModel } from 'foundry-orm';
2
3@Entity('users')  // Maps to 'users' table
4export class User extends BaseModel {
5  // Model properties...
6}

The @Column Decorator

The @Column decorator maps class properties to database columns:

Basic Usage

1@Entity('users')
2export class User extends BaseModel {
3  @Column('id')
4  id!: number;
5
6  @Column('name')
7  name!: string;
8
9  @Column('email')
10  email!: string;
11}

Advanced Configuration

Pass an object to @Column for advanced configuration:

1@Entity('products')
2export class Product extends BaseModel {
3  @Column({ name: 'id', type: 'integer', primary: true })
4  id!: number;
5
6  @Column({ name: 'product_name', type: 'varchar' })
7  name!: string;
8
9  @Column({ name: 'price', type: 'decimal' })
10  price!: number;
11
12  @Column({ name: 'created_at', type: 'timestamp' })
13  createdAt!: Date;
14
15  @Column({ name: 'updated_at', type: 'timestamp', nullable: true })
16  updatedAt?: Date;
17}

BaseModel Methods

All models extend BaseModel, which provides CRUD methods:

Static Methods

find(id)

Find a record by its primary key:

1const user = await User.find(1);
2if (user) {
3  console.log(user.name);
4}

findAll()

Retrieve all records from the table:

1const users = await User.findAll();
2users.forEach(user => console.log(user.name));

create(data)

Create and save a new record:

1const user = await User.create({
2  name: 'John Doe',
3  email: '[email protected]'
4});
5console.log('Created user with ID:', user.id);

Instance Methods

save()

Save changes to an existing record or insert a new one:

1const user = await User.find(1);
2if (user) {
3  user.name = 'Jane Doe';
4  await user.save();
5  console.log('User updated');
6}

delete()

Delete a record from the database:

1const user = await User.find(1);
2if (user) {
3  await user.delete();
4  console.log('User deleted');
5}

Model Examples

User Model

models/User.ts
1import { Entity, Column, BaseModel } from 'foundry-orm';
2
3@Entity('users')
4export class User extends BaseModel {
5  @Column('id')
6  id!: number;
7
8  @Column('username')
9  username!: string;
10
11  @Column('email')
12  email!: string;
13
14  @Column('password_hash')
15  passwordHash!: string;
16
17  @Column({ name: 'is_active', type: 'boolean' })
18  isActive!: boolean;
19
20  @Column({ name: 'created_at', type: 'timestamp' })
21  createdAt!: Date;
22
23  @Column({ name: 'updated_at', type: 'timestamp', nullable: true })
24  updatedAt?: Date;
25}

Post Model

models/Post.ts
1import { Entity, Column, BaseModel } from 'foundry-orm';
2
3@Entity('posts')
4export class Post extends BaseModel {
5  @Column('id')
6  id!: number;
7
8  @Column('title')
9  title!: string;
10
11  @Column('content')
12  content!: string;
13
14  @Column('author_id')
15  authorId!: number;
16
17  @Column({ name: 'published', type: 'boolean' })
18  published!: boolean;
19
20  @Column({ name: 'published_at', type: 'timestamp', nullable: true })
21  publishedAt?: Date;
22
23  @Column({ name: 'created_at', type: 'timestamp' })
24  createdAt!: Date;
25}

Product Model with Custom Methods

models/Product.ts
1import { Entity, Column, BaseModel } from 'foundry-orm';
2
3@Entity('products')
4export class Product extends BaseModel {
5  @Column('id')
6  id!: number;
7
8  @Column('name')
9  name!: string;
10
11  @Column('description')
12  description!: string;
13
14  @Column('price')
15  price!: number;
16
17  @Column('stock')
18  stock!: number;
19
20  // Custom method
21  isInStock(): boolean {
22    return this.stock > 0;
23  }
24
25  // Custom method with logic
26  applyDiscount(percentage: number): number {
27    return this.price * (1 - percentage / 100);
28  }
29
30  // Custom static method
31  static async findInStock(): Promise<Product[]> {
32    const allProducts = await Product.findAll();
33    return allProducts.filter(p => p.stock > 0);
34  }
35}

Best Practices

✓ Do's

  • Use TypeScript's type system for better type safety
  • Define models in separate files (one model per file)
  • Use descriptive property names that match your domain
  • Add custom methods for business logic
  • Use the ! definite assignment assertion for required fields
  • Use ? for optional/nullable fields

✗ Don'ts

  • Don't forget to extend BaseModel
  • Don't forget the @Entity decorator
  • Don't forget to decorate properties with @Column
  • Don't mix database logic with business logic
  • Don't hardcode database connection in models

Next Steps