乐闻世界logo
搜索文章和话题

How to use in-memory database with TypeORM in NestJS

1个答案

1

Using an in-memory database with TypeORM in NestJS is primarily for rapid prototyping during development or for testing when you don't want to persist data to a real database. The following are the steps to use TypeORM with an in-memory database:

  1. Install Dependencies: First, ensure you have installed the NestJS-related TypeORM packages and database drivers. For in-memory databases, we typically use sqlite3 as it is designed to run efficiently in memory.
bash
npm install @nestjs/typeorm typeorm sqlite3
  1. Configure TypeORM: In your app.module.ts or corresponding module configuration, set up TypeORM to use SQLite's in-memory database. Here's an example configuration:
typescript
import { Module } from '@nestjs/common'; import { TypeOrmModule } from '@nestjs/typeorm'; @Module({ imports: [ TypeOrmModule.forRoot({ type: 'sqlite', database: ':memory:', // Specifies the database as an in-memory database entities: [/* Your entity class locations */], synchronize: true, // Note: Only for development environments }), // ... other modules ], }) export class AppModule {}

In this configuration:

  • type is set to sqlite as we are using SQLite for our in-memory database.
  • database is set to :memory: which instructs SQLite to create an in-memory database.
  • entities array should include all your application's entity classes.
  • synchronize is set to true, which automatically creates database tables when the application starts. This is very convenient but should only be used in development as it may cause data loss in production.
  1. Define Entities: Create entities in your application that map to database tables. For example:
typescript
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm'; @Entity() export class User { @PrimaryGeneratedColumn() id: number; @Column() name: string; @Column() email: string; }
  1. Use Repository for Operations: In your services, inject the repositories for these entities and use them for CRUD operations. For example:
typescript
import { Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; import { User } from './user.entity'; @Injectable() export class UserService { constructor( @InjectRepository(User) private userRepository: Repository<User>, ) {} findAll(): Promise<User[]> { return this.userRepository.find(); } // ... other CRUD methods }

When using an in-memory database for testing, your data is lost upon each application restart, which is useful for certain test scenarios as it ensures test isolation.

The above are the general steps to configure an in-memory database with TypeORM in NestJS. This allows you to quickly start development and testing without worrying about persistent data storage.

2024年6月29日 12:07 回复

你的答案