typeorm-entities
TypeORM entity definition patterns
What this skill does
# TypeORM Entities Skill
Patterns for defining TypeORM entities.
## Basic Entities
### Simple Entity
```typescript
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
UpdateDateColumn,
} from 'typeorm'
@Entity('users')
export class User {
@PrimaryGeneratedColumn('uuid')
id: string
@Column({ unique: true })
email: string
@Column({ nullable: true })
name: string
@Column({ default: true })
active: boolean
@CreateDateColumn()
createdAt: Date
@UpdateDateColumn()
updatedAt: Date
}
```
### Column Types
```typescript
@Entity()
export class Example {
@PrimaryGeneratedColumn('uuid')
id: string
// Strings
@Column()
name: string
@Column({ length: 500 })
description: string
@Column('text')
longText: string
// Numbers
@Column('int')
count: number
@Column('decimal', { precision: 10, scale: 2 })
price: number
@Column('bigint')
largeNumber: string // bigint stored as string
// Boolean
@Column('boolean', { default: false })
isActive: boolean
// Dates
@Column('timestamp')
eventDate: Date
@Column('date')
birthDate: Date
// JSON
@Column('jsonb')
metadata: Record<string, any>
// Arrays (PostgreSQL)
@Column('text', { array: true })
tags: string[]
// Enum
@Column({
type: 'enum',
enum: UserRole,
default: UserRole.USER,
})
role: UserRole
}
enum UserRole {
ADMIN = 'admin',
USER = 'user',
GUEST = 'guest',
}
```
### Primary Keys
```typescript
// UUID (recommended)
@PrimaryGeneratedColumn('uuid')
id: string
// Auto-increment
@PrimaryGeneratedColumn()
id: number
// Identity (PostgreSQL)
@PrimaryGeneratedColumn('identity')
id: number
// Custom primary key
@PrimaryColumn()
id: string
// Composite primary key
@Entity()
export class OrderItem {
@PrimaryColumn()
orderId: string
@PrimaryColumn()
productId: string
@Column()
quantity: number
}
```
## Relations
### One-to-One
```typescript
@Entity()
export class User {
@PrimaryGeneratedColumn('uuid')
id: string
@OneToOne(() => Profile, profile => profile.user, {
cascade: true,
eager: false,
})
profile: Profile
}
@Entity()
export class Profile {
@PrimaryGeneratedColumn('uuid')
id: string
@Column({ nullable: true })
bio: string
@OneToOne(() => User, user => user.profile, {
onDelete: 'CASCADE',
})
@JoinColumn()
user: User
@Column()
userId: string
}
```
### One-to-Many / Many-to-One
```typescript
@Entity()
export class User {
@PrimaryGeneratedColumn('uuid')
id: string
@OneToMany(() => Post, post => post.author)
posts: Post[]
}
@Entity()
export class Post {
@PrimaryGeneratedColumn('uuid')
id: string
@Column()
title: string
@ManyToOne(() => User, user => user.posts, {
onDelete: 'CASCADE',
})
@JoinColumn({ name: 'author_id' })
author: User
@Column({ name: 'author_id' })
authorId: string
}
```
### Many-to-Many
```typescript
// Implicit join table
@Entity()
export class Post {
@PrimaryGeneratedColumn('uuid')
id: string
@ManyToMany(() => Category, category => category.posts)
@JoinTable({
name: 'post_categories',
joinColumn: { name: 'post_id', referencedColumnName: 'id' },
inverseJoinColumn: { name: 'category_id', referencedColumnName: 'id' },
})
categories: Category[]
}
@Entity()
export class Category {
@PrimaryGeneratedColumn('uuid')
id: string
@Column()
name: string
@ManyToMany(() => Post, post => post.categories)
posts: Post[]
}
// Explicit join table (with extra columns)
@Entity()
export class PostTag {
@PrimaryColumn()
postId: string
@PrimaryColumn()
tagId: string
@Column({ default: () => 'CURRENT_TIMESTAMP' })
createdAt: Date
@ManyToOne(() => Post, post => post.tags, { onDelete: 'CASCADE' })
@JoinColumn({ name: 'postId' })
post: Post
@ManyToOne(() => Tag, tag => tag.posts, { onDelete: 'CASCADE' })
@JoinColumn({ name: 'tagId' })
tag: Tag
}
```
### Self-Referencing
```typescript
@Entity()
export class Category {
@PrimaryGeneratedColumn('uuid')
id: string
@Column()
name: string
@Column({ nullable: true })
parentId: string
@ManyToOne(() => Category, category => category.children)
@JoinColumn({ name: 'parentId' })
parent: Category
@OneToMany(() => Category, category => category.parent)
children: Category[]
}
```
## Indexes
```typescript
@Entity()
@Index(['email'])
@Index(['organizationId', 'email'], { unique: true })
export class User {
@PrimaryGeneratedColumn('uuid')
id: string
@Index()
@Column()
email: string
@Index()
@Column()
organizationId: string
// Partial index (PostgreSQL)
@Index({ where: '"active" = true' })
@Column()
active: boolean
}
```
## Entity Inheritance
### Single Table Inheritance
```typescript
@Entity()
@TableInheritance({ column: { type: 'varchar', name: 'type' } })
export abstract class Content {
@PrimaryGeneratedColumn('uuid')
id: string
@Column()
title: string
}
@ChildEntity()
export class Article extends Content {
@Column()
body: string
}
@ChildEntity()
export class Video extends Content {
@Column()
url: string
@Column()
duration: number
}
```
### Embedded Entities
```typescript
export class Address {
@Column()
street: string
@Column()
city: string
@Column()
country: string
}
@Entity()
export class User {
@PrimaryGeneratedColumn('uuid')
id: string
@Column(() => Address)
address: Address
}
```
## Entity Listeners
```typescript
@Entity()
export class User {
@PrimaryGeneratedColumn('uuid')
id: string
@Column()
password: string
@BeforeInsert()
async hashPassword() {
this.password = await bcrypt.hash(this.password, 10)
}
@BeforeUpdate()
async hashPasswordOnUpdate() {
if (this.password) {
this.password = await bcrypt.hash(this.password, 10)
}
}
@AfterLoad()
async loadRelatedData() {
// Called after entity is loaded
}
@AfterInsert()
logInsert() {
console.log('User inserted:', this.id)
}
}
```
## Integration
Used by:
- `backend-developer` agent
- `fullstack-developer` agent
- `database-developer` agent
Related in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.