NestJS Enterprise Backend APIs · บทเรียน

ที่เก็บข้อมูล TypeORM แบบกำหนดเอง

สร้างที่เก็บข้อมูลแบบกำหนดเองเพื่อห่อหุ้มคำค้นฐานข้อมูลที่ซับซ้อน และปรับปรุงการจัดระเบียบโค้ดกับการนำกลับมาใช้ใหม่

บทเรียน 1 จาก 310 ขั้นตอน

ที่เก็บข้อมูล TypeORM แบบกำหนดเอง เป็นบทเรียน NestJS Enterprise Backend APIs ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 3 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน NestJS Enterprise Backend APIs และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส NestJS Enterprise Backend APIs มีบทเรียนทั้งหมด 3 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Beyond Basic CRUD

TypeORM's default Repository offers basic operations like save, find, and delete. These are great for simple tasks.

However, real-world applications often need more complex queries or domain-specific data retrieval logic.

Encapsulating Complex Queries

Without custom repositories, complex database queries might end up directly in your service layer. This can make services bloated and harder to maintain.

  • Cleaner Services: Services focus on business logic, not database specifics.
  • Reusability: Complex queries can be reused across different parts of your application.
  • Testability: Easier to test database interactions in isolation.

Creating a Custom Repository

To create a custom repository, you define a class that extends TypeORM's Repository<Entity>. You must also decorate it with @EntityRepository(Entity) to link it to a specific entity.

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

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

  @Column()
  name: string;

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

  @Column({ default: true })
  isActive: boolean;
}

// src/user/user.repository.ts
import { EntityRepository, Repository } from 'typeorm';
import { User } from './user.entity';

@EntityRepository(User)
export class UserRepository extends Repository<User> {
  // Custom methods will go here
}

Injecting the Custom Repository

Once defined, you can inject your custom repository into NestJS services or controllers using the @InjectRepository() decorator.

Remember to pass your custom repository class as an argument to @InjectRepository().

import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { UserRepository } from './user.repository';
import { User } from './user.entity';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(UserRepository)
    private userRepository: UserRepository,
  ) {}

  async findAllActive(): Promise<User[]> {
    // This method will be defined in the custom repo
    return this.userRepository.findActiveUsers();
  }
}

Adding a Custom Method

Inside your custom repository, you can add methods that encapsulate specific query logic. These methods can use the default Repository methods or TypeORM's Query Builder.

Let's add methods to find all active users and find a user by email.

// src/user/user.repository.ts (updated)
import { EntityRepository, Repository } from 'typeorm';
import { User } from './user.entity';

@EntityRepository(User)
export class UserRepository extends Repository<User> {
  async findActiveUsers(): Promise<User[]> {
    return this.find({ isActive: true });
  }

  async findByEmail(email: string): Promise<User | undefined> {
    return this.findOne({ email });
  }
}

Custom Repo Workflow

Here's the typical flow: you define your Entity, then your Custom Repository extending Repository<Entity>, and finally inject it into your Service.

// 1. user.entity.ts
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
@Entity() export class User {
  @PrimaryGeneratedColumn() id: number;
  @Column() name: string;
  @Column({ unique: true }) email: string;
  @Column({ default: true }) isActive: boolean;
}

// 2. user.repository.ts
import { EntityRepository, Repository } from 'typeorm';
import { User } from './user.entity';
@EntityRepository(User)
export class UserRepository extends Repository<User> {
  async findActiveUsers(): Promise<User[]> {
    return this.find({ isActive: true });
  }
}

// 3. user.service.ts
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { UserRepository } from './user.repository';
import { User } from './user.entity';
@Injectable()
export class UserService {
  constructor(
    @InjectRepository(UserRepository)
    private userRepository: UserRepository,
  ) {}
  async getAllActive(): Promise<User[]> {
    return this.userRepository.findActiveUsers();
  }
}

Module Configuration

For NestJS to properly manage the TypeORM repositories, your module needs to import TypeOrmModule.forFeature() with your entities. The @EntityRepository decorator handles the TypeORM-side registration, allowing injection.

// src/user/user.module.ts
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { User } from './user.entity';
import { UserService } from './user.service';
import { UserController } from './user.controller';

@Module({
  imports: [
    TypeOrmModule.forFeature([User]) // Only entities here
  ],
  providers: [UserService, UserController],
  exports: [UserService] // Export service if used elsewhere
})
export class UserModule {}

Leveraging Query Builder

For more complex queries, custom repositories often use TypeORM's powerful Query Builder. This allows you to construct dynamic queries with joins, conditions, and more.

Let's add a method to find users who are active and have a specific name pattern.

// src/user/user.repository.ts (extended)
import { EntityRepository, Repository } from 'typeorm';
import { User } from './user.entity';
import { MoreThan } from 'typeorm'; // Example for complex query

@EntityRepository(User)
export class UserRepository extends Repository<User> {
  async findActiveUsers(): Promise<User[]> {
    return this.find({ isActive: true });
  }

  async findByNamePattern(pattern: string): Promise<User[]> {
    return this.createQueryBuilder('user')
      .where('user.name LIKE :pattern', { pattern: `%${pattern}%` })
      .andWhere('user.isActive = :isActive', { isActive: true })
      .getMany();
  }
}

Check Your Understanding

Consider the following custom repository and service:

// product.repository.ts
import { EntityRepository, Repository, MoreThan } from 'typeorm';
import { Product } from './product.entity'; // Assume Product entity exists

@EntityRepository(Product)
export class ProductRepository extends Repository<Product> {
  async findAvailableProducts(): Promise<Product[]> {
    return this.find({ where: { stock: MoreThan(0), isActive: true } });
  }
}

// product.service.ts
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { ProductRepository } from './product.repository';
import { Product } from './product.entity'; // Assume Product entity exists

@Injectable()
export class ProductService {
  constructor(
    @InjectRepository(ProductRepository)
    private productRepo: ProductRepository,
  ) {}

  async getProducts(): Promise<Product[]> {
    return this.productRepo.findAvailableProducts();
  }
}

Custom Repositories Summary

In this lesson, we explored custom TypeORM repositories. We learned that they are a powerful pattern to:

  • Encapsulate complex, reusable database query logic.
  • Keep your NestJS services clean and focused on business rules.
  • Improve code organization, reusability, and testability.

By extending TypeORM's Repository and using @EntityRepository, you can define domain-specific methods that make your data access layer much more robust.

เริ่มต้นได้ฟรี

เรียนรู้ TypeScript ด้วย AI tutor — ฟรี

เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป

คอร์ส
20
บทเรียน
76

คำถามที่พบบ่อย

บทเรียน “ที่เก็บข้อมูล TypeORM แบบกำหนดเอง” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “ที่เก็บข้อมูล TypeORM แบบกำหนดเอง” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส NestJS Enterprise Backend APIs ให้อัปเกรดเป็น CoddyKit PRO คอร์ส NestJS Enterprise Backend APIs มีบทเรียนทั้งหมด 3 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “ที่เก็บข้อมูล TypeORM แบบกำหนดเอง”

สร้างที่เก็บข้อมูลแบบกำหนดเองเพื่อห่อหุ้มคำค้นฐานข้อมูลที่ซับซ้อน และปรับปรุงการจัดระเบียบโค้ดกับการนำกลับมาใช้ใหม่ คุณปฏิบัติ NestJS Enterprise Backend APIs ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน NestJS Enterprise Backend APIs หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน NestJS Enterprise Backend APIs บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 3 บทเรียน

บทเรียน “ที่เก็บข้อมูล TypeORM แบบกำหนดเอง” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน NestJS Enterprise Backend APIs นี้ได้ไหม

ได้ บทเรียน NestJS Enterprise Backend APIs ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. ที่เก็บข้อมูล TypeORM แบบกำหนดเอง
  2. ธุรกรรมและการย้ายข้อมูล
  3. การเติมข้อมูลเริ่มต้นและการทดสอบฐานข้อมูล
← กลับไปที่ NestJS Enterprise Backend APIs