リリース・改善中
NestJS · Express ガイド · 4/6
この章は現在、英語でのみ提供しています。
Data enters a server through request bodies, gets validated, and ends up in a database. This chapter covers validation with ValidationPipe and class-validator, reading environment variables with the config module, and database access through an ORM.
Nest providers are singletons by default, shared across the whole app. Storing per-request values in service fields can leak data between users. Keep state that must outlive a request in a database or an external store such as Redis, and keep the server process stateless so multiple instances behave the same.
Describe request bodies with DTO (data transfer object) classes and attach rules with class-validator decorators.
npm i class-validator class-transformer// src/users/dto/create-user.dto.ts
import { IsEmail, IsInt, IsOptional, IsString, Length, Min } from "class-validator";
export class CreateUserDto {
@IsString()
@Length(2, 30)
name: string;
@IsEmail()
email: string;
@IsOptional()
@IsInt()
@Min(0)
age?: number;
}Register ValidationPipe globally in main.ts and every DTO received with @Body() is checked automatically; invalid input gets a 400 response listing the errors.
// src/main.ts
import { ValidationPipe } from "@nestjs/common";
import { NestFactory } from "@nestjs/core";
import { AppModule } from "./app.module";
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalPipes(
new ValidationPipe({
whitelist: true, // strip properties not in the DTO
forbidNonWhitelisted: true, // or reject them with 400
transform: true, // turn plain objects into DTO instances
}),
);
await app.listen(process.env.PORT ?? 3000);
}
bootstrap();In a controller, just type the parameter: create(@Body() dto: CreateUserDto). For updates, PartialType(CreateUserDto) from @nestjs/mapped-types makes every property optional; nest g resource generates UpdateUserDto this way.
Keep database URLs and secrets out of code. ConfigModule from @nestjs/config loads a .env file plus real environment variables and exposes them through ConfigService.
npm i @nestjs/configWith ConfigModule.forRoot({ isGlobal: true }) in the root module (shown below), any provider can inject ConfigService and call this.config.get<string>("DATABASE_URL"). Real environment variables take precedence over .env, and stays out of version control.
.envNest provides an official TypeORM integration, @nestjs/typeorm. For PostgreSQL, install it with the driver.
npm i @nestjs/typeorm typeorm pgDefine tables as entity classes, configure the connection in the root module, and register entities in feature modules.
// src/users/entities/user.entity.ts
import { Column, Entity, PrimaryGeneratedColumn } from "typeorm";
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@Column({ unique: true })
email: string;
}// src/app.module.ts
import { Module } from "@nestjs/common";
import { ConfigModule, ConfigService } from "@nestjs/config";
import { TypeOrmModule } from "@nestjs/typeorm";
import { UsersModule } from "./users/users.module";
@Module({
imports: [
ConfigModule.forRoot({ isGlobal: true }),
TypeOrmModule.forRootAsync({
inject: [ConfigService],
useFactory: (config: ConfigService) => ({
type: "postgres",
url: config.get<string>("DATABASE_URL"),
autoLoadEntities: true,
synchronize: false, // use migrations in production
}),
}),
UsersModule,
],
})
export class AppModule {}Add TypeOrmModule.forFeature([User]) to the imports of UsersModule, then inject the repository with @InjectRepository.
import { Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import { CreateUserDto } from "./dto/create-user.dto";
import { User } from "./entities/user.entity";
@Injectable()
export class UsersService {
constructor(@InjectRepository(User) private readonly users: Repository<User>) {}
findAll() {
return this.users.find();
}
create(dto: CreateUserDto) {
return this.users.save(this.users.create(dto));
}
}synchronize: true alters the schema to match your entities. It is handy early on but can drop data, so turn it off in production and manage the schema with TypeORM migrations.
Prisma is an ORM where you describe models in schema.prisma and generate a typed client from it. Start with npm i -D prisma and npx prisma init, and create and apply migrations with npx prisma migrate dev. There is no official Nest module; the usual pattern is a PrismaService provider wrapping the generated PrismaClient, connecting in onModuleInit, and injected into other services. Client output location and setup differ between Prisma releases, so follow the NestJS guide in Prisma's docs.
Express ships no validation or data layer. Parse bodies with express.json(), validate with a library such as Zod or Joi, and expose your ORM or driver from a module your routers import. You design yourself what Nest organizes with modules and dependency injection.
ValidationPipe.ConfigModule and ConfigService.@nestjs/typeorm and inject repositories; wire Prisma through your own PrismaService.
コメント 0件
ログイン · ログインするとコメントできます。
最初のコメントを書いてみましょう。