Community코딩 & 개발github.com

mindrally/typeorm

TypeORM 개발 가이드라인 - TypeScript와 JavaScript를 위한 다양한 데이터베이스를 지원하는 완전한 기능의 ORM

typeorm란 무엇인가요?

이 스킬은 TypeORM을 사용하여 개발할 때 필요한 모범 사례와 가이드라인을 제공합니다. TypeORM은 TypeScript와 JavaScript를 지원하는 강력한 ORM(Object-Relational Mapping) 라이브러리로, MySQL, PostgreSQL, SQLite, MongoDB 등 여러 데이터베이스를 지원합니다. 이 스킬은 엔티티 정의, 리포지토리 패턴, 마이그레이션, 쿼리 빌더, 관계 매핑 등 TypeORM의 핵심 기능들을 효과적으로 활용하는 방법을 설명합니다. 개발자들은 이 가이드를 통해 TypeORM을 더 체계적으로 사용하고, 일반적인 함정을 피하며, 생산성을 높일 수 있습니다. 특히 복잡한 데이터베이스 관계와 트랜잭션 처리가 필요한 프로젝트에서 유용합니다.

지원 대상~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/mindrally/skills/tree/main/skills/typeorm

Installed? Explore more 코딩 & 개발 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

즐겨 사용하는 AI에게 물어보기

이 에이전트 스킬이 미리 로드된 새 채팅을 엽니다.

문서

typeorm은(는) 무엇을 하나요?

TypeORM을 사용한 개발 가이드라인 - TypeScript와 JavaScript를 위한 완전한 기능의 ORM으로 여러 데이터베이스를 지원합니다.

개요

TypeORM은 TypeScript와 JavaScript(ES5, ES6, ES7, ES8) 환경에서 사용할 수 있는 ORM 라이브러리입니다. MySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, Oracle, MongoDB 등 다양한 데이터베이스 엔진을 지원합니다.

주요 기능

  • 데코레이터 기반 엔티티 정의: TypeScript 데코레이터를 사용하여 직관적으로 엔티티를 정의할 수 있습니다.
  • 액티브 레코드와 데이터 매퍼 패턴: 두 가지 패턴을 모두 지원하여 유연한 개발이 가능합니다.
  • 마이그레이션: 데이터베이스 스키마 변경을 체계적으로 관리할 수 있습니다.
  • 쿼리 빌더: SQL 쿼리를 프로그래밍 방식으로 안전하게 작성할 수 있습니다.
  • 관계 매핑: 일대일, 일대다, 다대다 관계를 손쉽게 정의하고 관리할 수 있습니다.
  • 트랜잭션 지원: ACID 트랜잭션을 완벽하게 지원합니다.

시작하기

npm install typeorm --save
npm install reflect-metadata --save
npm install @types/node --save-dev

tsconfig.json에 다음 설정을 추가하세요:

{
  "emitDecoratorMetadata": true,
  "experimentalDecorators": true
}

엔티티 정의 예시

import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';

@Entity()
export class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  firstName: string;

  @Column()
  lastName: string;

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

데이터 소스 설정

import { DataSource } from 'typeorm';

const AppDataSource = new DataSource({
  type: 'postgres',
  host: 'localhost',
  port: 5432,
  username: 'test',
  password: 'test',
  database: 'test',
  entities: [User],
  synchronize: true,
  logging: false,
});

리포지토리 사용

const userRepository = AppDataSource.getRepository(User);

// 사용자 생성
const user = new User();
user.firstName = 'John';
user.lastName = 'Doe';
user.email = '[email protected]';
await userRepository.save(user);

// 사용자 조회
const users = await userRepository.find({ where: { firstName: 'John' } });

// 사용자 업데이트
await userRepository.update({ id: 1 }, { firstName: 'Jane' });

// 사용자 삭제
await userRepository.delete({ id: 1 });

관계 정의

import { Entity, PrimaryGeneratedColumn, Column, OneToMany, ManyToOne } from 'typeorm';

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

  @Column()
  title: string;

  @Column('text')
  content: string;

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

@Entity()
export class User {
  @PrimaryGeneratedColumn()
  id: number;

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

마이그레이션

# 마이그레이션 생성
npx typeorm migration:create ./src/migration/InitialMigration

# 마이그레이션 실행
npx typeorm migration:run

# 마이그레이션 되돌리기
npx typeorm migration:revert

쿼리 빌더 사용

const users = await AppDataSource
  .getRepository(User)
  .createQueryBuilder('user')
  .leftJoinAndSelect('user.posts', 'post')
  .where('user.firstName = :name', { name: 'John' })
  .orderBy('user.id', 'DESC')
  .getMany();

트랜잭션 처리

await AppDataSource.transaction(async (transactionalEntityManager) => {
  const user = new User();
  user.firstName = 'John';
  user.lastName = 'Doe';
  await transactionalEntityManager.save(user);

  const post = new Post();
  post.title = 'My first post';
  post.content = 'Hello, world!';
  post.author = user;
  await transactionalEntityManager.save(post);
});

모범 사례

  1. 엔티티 네이밍 규칙: 엔티티 클래스는 단수형, 데이터베이스 테이블은 복수형으로 지정하세요.
  2. 마이그레이션 사용: synchronize: true는 개발 환경에서만 사용하고, 프로덕션에서는 마이그레이션을 사용하세요.
  3. 지연 로딩 활용: 필요할 때만 관계 데이터를 로드하여 성능을 최적화하세요.
  4. 인덱스 추가: 자주 쿼리되는 컬럼에는 인덱스를 추가하세요.
  5. 트랜잭션 사용: 여러 작업이 원자적으로 실행되어야 할 때는 트랜잭션을 사용하세요.

참고 자료

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

mindrally/accessibility-a11y

Implement web accessibility (a11y) best practices following WCAG guidelines to create inclusive, accessible user interfaces.

mindrally/chrome-extension-development

Expert guidelines for Chrome extension development with Manifest V3, covering security, performance, and best practices. Use when building browser extensions, creating popup UIs, implementing content scripts, working with Chrome APIs, managing extension permissions, or publishing to Chrome Web Store.

mindrally/computer-vision-opencv

Expert guidance for computer vision development using OpenCV, PyTorch, and modern deep learning techniques for image and video processing.

mindrally/data-analysis-jupyter

Expert guidance for data analysis, visualization, and Jupyter Notebook development with pandas, matplotlib, seaborn, and numpy.

mindrally/deep-learning-pytorch

Expert guidance for deep learning, transformers, diffusion models, and LLM development with PyTorch, Transformers, Diffusers, and Gradio.

mindrally/expo-react-native-typescript

Expert in Expo React Native TypeScript mobile development with best practices

mindrally/fastapi-python

Expert in FastAPI Python development with best practices for APIs and async operations

mindrally/framer-motion

Expert guidelines for building performant animations with Framer Motion/Motion library in React applications

mindrally/htmx

HTMX development guidelines for building dynamic web applications with minimal JavaScript using HTML attributes.

mindrally/jwt-security

Guidelines for implementing JWT authentication with security best practices for token creation, validation, and storage

mindrally/machine-learning

Machine learning development with JAX, functional programming patterns, and high-performance computing.

mindrally/mysql-best-practices

MySQL development best practices for schema design, query optimization, and database administration

mindrally/nextjs-react-typescript

Expert in TypeScript, Node.js, Next.js App Router, React, Shadcn UI, Radix UI and Tailwind

mindrally/nextjs-typescript-tailwindcss-supabase

Full-stack Next.js 14 development with TypeScript, TailwindCSS, and Supabase for building production-ready web applications.

mindrally/odoo-development

Expert guidance for Odoo ERP development including Python ORM, XML views, and module architecture

mindrally/puppeteer-automation

Expert guidance for browser automation using Puppeteer with best practices for web scraping, testing, screenshot capture, and JavaScript execution in headless Chrome.

mindrally/redis-best-practices

Redis development best practices for caching, data structures, and high-performance key-value operations

mindrally/scrapy-web-scraping

Expert guidance for building web scrapers and crawlers using the Scrapy Python framework with best practices for spider development, data extraction, and pipeline management.

mindrally/scss-best-practices

SCSS/Sassy CSS best practices and coding guidelines for maintainable, scalable stylesheets

mindrally/web-scraping

Expert in web scraping and data extraction with Python tools

관련 스킬