typeorm
Use when defining TypeORM entities, writing migrations, or building repository/query-builder code in TypeScript. Covers entity and relation decorators, the Data Mapper pattern, migrations, the query builder, transactions, and multi-database configuration.
- License 许可
- MIT
- 最近更新
- 2026-11-14
- Stars
- ★ 3
- Forks
- 0
01 前言 Front Matter
- name
- typeorm
- description
- Use when defining TypeORM entities, writing migrations, or building repository/query-builder code in TypeScript. Covers entity and relation decorators, the Data Mapper pattern, migrations, the query builder, transactions, and multi-database configuration.
02 资源文件 4
- 参考文档evals/evals.json3.2 KB
- 参考文档reference.md12.6 KB
- 脚本scripts/new-entity.sh1.5 KB
- 脚本scripts/new-migration.sh2.1 KB
03 SKILL.md 正文
TypeORM Development Guidelines
You are an expert in TypeORM, TypeScript, and database design with a focus on the Data Mapper pattern and enterprise application architecture.
Core Principles
- TypeORM supports both Active Record and Data Mapper patterns
- Uses TypeScript decorators for entity and column definitions
- Supports MySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, Oracle, and more
- Works in Node.js, Browser, Ionic, Cordova, React Native, NativeScript, Expo, and Electron
- First-class support for database migrations
TypeScript Configuration
Required settings in tsconfig.json:
{
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"strict": true,
"target": "ES2020",
"module": "commonjs",
"moduleResolution": "node"
}
}
experimentalDecorators and emitDecoratorMetadata are both mandatory — without
them decorators won't compile and column metadata won't resolve.
Entity Definition
A representative entity uses a generated primary key, typed @Columns, and the
managed timestamp columns:
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
UpdateDateColumn,
} from 'typeorm';
@Entity('users')
export class User {
@PrimaryGeneratedColumn()
id!: number;
@Column({ type: 'varchar', length: 255, unique: true })
email!: string;
@Column({ type: 'varchar', length: 255, nullable: true })
name!: string | null;
@Column({ type: 'boolean', default: true })
isActive!: boolean;
@CreateDateColumn()
createdAt!: Date;
@UpdateDateColumn()
updatedAt!: Date;
}
For the full primary-key options (UUID, custom, composite), the complete column decorator/option set (numeric, enum, JSON, soft-delete, version), and all relation types (one-to-one, one-to-many/many-to-one, many-to-many), see reference.md.
Data Source Configuration
// data-source.ts
import { DataSource } from 'typeorm';
import { User } from './entities/User';
import { Post } from './entities/Post';
export const AppDataSource = new DataSource({
type: 'postgres',
host: process.env.DB_HOST || 'localhost',
port: parseInt(process.env.DB_PORT || '5432'),
username: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
// Entity configuration
entities: [User, Post],
// Or use glob pattern: entities: ["src/entities/**/*.ts"]
// Migrations
migrations: ['src/migrations/**/*.ts'],
// Synchronize - NEVER use in production
synchronize: false,
// Logging
logging: process.env.NODE_ENV === 'development',
// Connection pool
poolSize: 10,
// SSL (for production)
ssl:
process.env.NODE_ENV === 'production'
? { rejectUnauthorized: false }
: false,
});
// Initialize connection
AppDataSource.initialize()
.then(() => console.log('Data Source initialized'))
.catch((error) => console.error('Error initializing Data Source:', error));
Quick Guidance
- Get a repository with
AppDataSource.getRepository(Entity), then usefind,findOne,create,save,update,delete, andsoftDelete. - Load relations explicitly with
relations: ['posts'](or aleftJoinAndSelectin the query builder) instead ofeager: true, to avoid N+1 query storms. - Never use
synchronize: truein production — generate and run migrations for every schema change. - Index columns you frequently filter or look up via
@Index(). - Always
release()a manually createdQueryRunnerin afinallyblock.
Full API detail — repository methods, custom repositories, the query builder, migrations, transactions, framework integration, and best practices — lives in the reference.
Additional resources
- For the full entity/relation/query-builder/migration reference, see reference.md
- To scaffold a new entity file, run scripts/new-entity.sh
<EntityName> - To scaffold a new timestamped migration, run scripts/new-migration.sh
<MigrationName>
04 同仓库更多 Skills
designing-in-patterns
Use when designing, planning or auditing UI against a component library — naming surfaces with the repo's pattern vocabulary, deciding reuse versus extend versus new, exploring compositions, or writing the reuse table (component-plan.md, a spec's `## Reuse`, a UI audit). Carries the design method; the repo's own vocabulary, bundle and board rules come from project-context and the designer override.
hono-api
Use when building or extending REST APIs with Hono + @hono/zod-openapi. Covers schema-first route declaration with createRoute, feature-grouped composable routers, a class-based service layer behind interfaces, the strategy pattern for multi-event webhooks, typed request validation, and auto-generated OpenAPI docs.
electrodb
Use when defining DynamoDB entities, modeling indexes, or writing queries/mutations with the ElectroDB ORM. Covers entity schema, access patterns, CRUD operations, update expressions, and single-table design patterns.
atomic-design
Use when structuring or decomposing any frontend UI into reusable components, regardless of framework. Applies Brad Frost's atomic design methodology — atoms, molecules, organisms, templates, and pages — to guide consistent component hierarchy, naming, and composition decisions.
writing-docs
Use when writing, restructuring, or reviewing any prose documentation — a tutorial, how-to guide, reference page, or explanation/conceptual doc — for a public docs site (e.g. Mintlify MDX, docs/, README material), a getting-started guide, an API/CLI reference page, or a "why we built it this way" conceptual page. Applies the Diátaxis framework (see https://diataxis.fr/) — every document belongs to exactly one of the four quadrants (tutorial / how-to guide / reference / explanation), and mixing quadrants inside one document is the single most common documentation failure. Covers the four-quadrant compass for picking the right form, per-quadrant structure templates, an anti-pattern list for quadrant drift, and generic voice/craft rules — repo-specific voice and target output format (e.g. Mintlify MDX) are resolved from the repo's docs-manifest (falling back to project-context), never hardcoded here.
writing-adrs
Use when authoring an Architecture Decision Record (ADR) — a short document that captures one significant, hard-to-reverse technical or architectural decision, its context, and its consequences. Triggered by the sdlc ADR pipeline (the knowledge-engineer agent behind /sdlc:docs seed adr and /sdlc:docs distill) when generating an ADR from a story, and by anyone hand-authoring an ADR under docs/adr/ today. Covers why ADRs are kept short and inverted-pyramid, the required sections (Title, Status, Decision, Context, Alternatives Considered, Consequences), the proposed→accepted→superseded (or →rejected) status lifecycle and the never-edit-only-supersede immutability rule, the NNNN-decision-slug.md filename convention, and the ADR frontmatter fields (status, agents, source-stories) the pipeline reads to route a generated ADR into docs/adr/index.md.