Skip to content
OpenSmartRoute
Skillv1.0.0

typeorm

You are an expert in TypeORM, the ORM for TypeScript and JavaScript that supports PostgreSQL, MySQL, SQLite, MS SQL, and Oracle. You help developers define entities with decorators, build type-safe qu

by terminalskills(0) 0 installs
Free
Sign in to install

Free account. Installing gives you the manifest plus copy-paste snippets.

See reviews

About

Imported from terminalskills/skills (skills/typeorm/SKILL.md). Install upstream with npx skills add terminalskills/skills --skill typeorm. Copyright stays with the author (Apache-2.0).

TypeORM — TypeScript ORM for SQL Databases

You are an expert in TypeORM, the ORM for TypeScript and JavaScript that supports PostgreSQL, MySQL, SQLite, MS SQL, and Oracle. You help developers define entities with decorators, build type-safe queries with QueryBuilder, manage database migrations, handle relations (one-to-one, one-to-many, many-to-many), and use repository patterns for clean data access layers.

Core Capabilities

Entity Definition

import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn,
  ManyToOne, OneToMany, ManyToMany, JoinTable, Index, BeforeInsert } from "typeorm";

@Entity("users")
export class User {
  @PrimaryGeneratedColumn("uuid")
  id: string;

  @Column({ length: 100 })
  name: string;

  @Index({ unique: true })
  @Column()
  email: string;

  @Column({ select: false })
  passwordHash: string;

  @Column({ type: "enum", enum: ["user", "admin"], default: "user" })
  role: "user" | "admin";

  @Column({ type: "jsonb", nullable: true })
  profile: { bio?: string; avatar?: string };

  @OneToMany(() => Post, (post) => post.author)
  posts: Post[];

  @ManyToMany(() => Tag)
  @JoinTable()
  interests: Tag[];

  @CreateDateColumn()
  createdAt: Date;

  @UpdateDateColumn()
  updatedAt: Date;

  @BeforeInsert()
  normalizeEmail() {
    this.email = this.email.toLowerCase().trim();
  }
}

@Entity("posts")
export class Post {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  title: string;

  @Column({ type: "text" })
  body: string;

  @Column({ default: false })
  published: boolean;

  @ManyToOne(() => User, (user) => user.posts)
  author: User;

  @Column()
  authorId: string;

  @CreateDateColumn()
  createdAt: Date;
}

QueryBuilder

// Complex queries with type safety
const posts = await dataSource
  .getRepository(Post)
  .createQueryBuilder("post")
  .leftJoinAndSelect("post.author", "author")
  .where("post.published = :published", { published: true })
  .andWhere("author.role = :role", { role: "admin" })
  .orderBy("post.createdAt", "DESC")
  .skip(20)
  .take(10)
  .getMany();

// Subquery
const topAuthors = await dataSource
  .getRepository(User)
  .createQueryBuilder("user")
  .addSelect((subQuery) =>
    subQuery
      .select("COUNT(post.id)", "postCount")
      .from(Post, "post")
      .where("post.authorId = user.id"),
    "postCount"
  )
  .orderBy("postCount", "DESC")
  .limit(10)
  .getRawMany();

// Transactions
await dataSource.transaction(async (manager) => {
  const user = manager.create(User, { name: "Alice", email: "alice@example.com" });
  await manager.save(user);
  const post = manager.create(Post, { title: "First Post", author: user });
  await manager.save(post);
});

Migrations

# Generate migration from entity changes
npx typeorm migration:generate src/migrations/AddUserProfile -d src/data-source.ts

# Run migrations
npx typeorm migration:run -d src/data-source.ts

# Revert last migration
npx typeorm migration:revert -d src/data-source.ts

Installation

npm install typeorm reflect-metadata
npm install pg                            # PostgreSQL driver
# Add to tsconfig.json: "emitDecoratorMetadata": true, "experimentalDecorators": true

Best Practices

  1. Migrations over sync — Never use synchronize: true in production; use generated migrations for schema changes
  2. QueryBuilder for complex queries — Use repositories for simple CRUD, QueryBuilder for joins/subqueries/aggregations
  3. Select only needed fields — Use .select(["user.id", "user.name"]) to avoid fetching large columns
  4. Eager vs lazy relations — Default to lazy; use leftJoinAndSelect only when you need the relation
  5. Transactions for consistency — Wrap multi-entity operations in dataSource.transaction()
  6. Entity listeners — Use @BeforeInsert, @BeforeUpdate for data normalization and validation
  7. Repository pattern — Create custom repositories for complex query logic; keeps services clean
  8. Connection pooling — Configure extra: { max: 20 } in data source options; match your expected concurrency

Use it

Copy one of these into your project. Installing also returns the manifest and these snippets.

yaml
targets:
  - https://api.opensmartroute.ai/api/v1/registry/terminalskills-skills-typeorm/manifest   # or paste the manifest below

Manifest

An Open Capability Manifest: the router reads it to know what this does, what it costs and when to pick it.

terminalskills-skills-typeorm.ocm.jsonjson
{
  "ocm": "1",
  "id": "terminalskills-skills-typeorm",
  "kind": "skill",
  "name": "typeorm",
  "description": "You are an expert in TypeORM, the ORM for TypeScript and JavaScript that supports PostgreSQL, MySQL, SQLite, MS SQL, and Oracle. You help developers define entities with decorators, build type-safe queries with QueryBuilder, manage database migrations, handle relations (one-to-one, one-to-many, many-to-many), and use repository patterns for clean data access layers.",
  "publisher": "terminalskills",
  "version": "1.0.0",
  "capabilities": {
    "domains": [
      "coding",
      "data_analysis"
    ],
    "tags": [
      "skill-md",
      "orm",
      "typescript",
      "database",
      "sql",
      "postgres",
      "mysql",
      "migrations",
      "skills-sh"
    ],
    "languages": [
      "en"
    ]
  },
  "quality_prior": 0.6,
  "examples": [
    "You are an expert in TypeORM, the ORM for TypeScript and JavaScript that supports PostgreSQL, MySQL, SQLite, MS SQL, and Oracle. You help developers define entities with decorators, build type-safe queries with QueryBuilder, manage database migrations, handle relations (one-to-one, one-to-many, many-to-many), and use repository patterns for clean data access layers."
  ],
  "primary": false,
  "metadata": {
    "source": {
      "provider": "skills.sh",
      "repository": "https://github.com/terminalskills/skills",
      "path": "skills/typeorm/SKILL.md",
      "ref": "HEAD",
      "url": "https://github.com/terminalskills/skills/blob/HEAD/skills/typeorm/SKILL.md",
      "key": "terminalskills/skills/skills/typeorm/SKILL.md"
    },
    "license": "Apache-2.0"
  },
  "instructions": "# TypeORM — TypeScript ORM for SQL Databases\n\nYou are an expert in TypeORM, the ORM for TypeScript and JavaScript that supports PostgreSQL, MySQL, SQLite, MS SQL, and Oracle. You help developers define entities with decorators, build type-safe queries with QueryBuilder, manage database migrations, handle relations (one-to-one, one-to-many, many-to-many), and use repository patterns for clean data access layers.\n\n## Core Capabilities\n\n### Entity Definition\n\n```typescript\nimport { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn,\n  ManyToOne, OneToMany, ManyToMany, Join",
  "cost": {
    "context_tokens": 1037
  }
}

Fetch it by URL: GET /api/v1/registry/terminalskills-skills-typeorm/manifest?version=1.0.0

Reviews

Star ratings from people who tried it. One review per account; edit yours any time.

No reviews yet. Install it, try it, and be the first to rate it.