NestJS 入门 — 学生管理系统模块

知识库
知识库文档
/tech-stacks/nestjs/examples/NestJS 入门 — 学生管理系统模块.md

文档

NestJS 入门 — 学生管理系统模块

目标

演示 NestJS 核心概念:模块化(Module)、控制器(Controller)、服务(Service)、依赖注入(DI)、DTO 验证。

1. 创建项目

nest new nest-demo
cd nest-demo

2. 生成学生模块

nest g resource students
# 选择 REST API, 生成 CRUD 入口点

3. 完整代码

src/students/dto/create-student.dto.ts

import { IsString, IsInt, Min, Max, IsEmail, IsOptional } from 'class-validator';

export class CreateStudentDto {
  @IsString()
  name: string;

  @IsInt()
  @Min(18)
  @Max(30)
  age: number;

  @IsEmail()
  email: string;

  @IsOptional()
  @IsString()
  major?: string;
}

src/students/students.service.ts

import { Injectable, NotFoundException } from '@nestjs/common';
import { CreateStudentDto } from './dto/create-student.dto';
import { UpdateStudentDto } from './dto/update-student.dto';

@Injectable()
export class StudentsService {
  private students = [];

  create(dto: CreateStudentDto) {
    const student = { id: Date.now(), ...dto, createdAt: new Date() };
    this.students.push(student);
    return student;
  }

  findAll() {
    return { count: this.students.length, data: this.students };
  }

  findOne(id: number) {
    const student = this.students.find(s => s.id === id);
    if (!student) throw new NotFoundException(`学生 #${id} 不存在`);
    return student;
  }

  update(id: number, dto: UpdateStudentDto) {
    const student = this.findOne(id);
    Object.assign(student, dto);
    return student;
  }

  remove(id: number) {
    const index = this.students.findIndex(s => s.id === id);
    if (index === -1) throw new NotFoundException(`学生 #${id} 不存在`);
    this.students.splice(index, 1);
    return { message: '已删除' };
  }
}

src/students/students.controller.ts

import { Controller, Get, Post, Body, Param, Delete, Put, ParseIntPipe, Query } from '@nestjs/common';
import { StudentsService } from './students.service';
import { CreateStudentDto } from './dto/create-student.dto';
import { UpdateStudentDto } from './dto/update-student.dto';

@Controller('students')
export class StudentsController {
  constructor(private readonly studentsService: StudentsService) {}

  @Post()
  create(@Body() dto: CreateStudentDto) {
    return this.studentsService.create(dto);
  }

  @Get()
  findAll() {
    return this.studentsService.findAll();
  }

  @Get(':id')
  findOne(@Param('id', ParseIntPipe) id: number) {
    return this.studentsService.findOne(id);
  }

  @Put(':id')
  update(@Param('id', ParseIntPipe) id: number, @Body() dto: UpdateStudentDto) {
    return this.studentsService.update(id, dto);
  }

  @Delete(':id')
  remove(@Param('id', ParseIntPipe) id: number) {
    return this.studentsService.remove(id);
  }
}

运行步骤

npm run start:dev
# 访问 http://localhost:3000/students

# 测试 POST
curl -X POST http://localhost:3000/students \
  -H "Content-Type: application/json" \
  -d '{"name":"张三","age":22,"email":"zhangsan@univ.edu.cn","major":"计算机科学"}'

预期输出

  • GET /students{"count":1,"data":[...]}
  • DTO 自动验证:age < 18 或 email 格式错误时返回 400 及详细错误信息
  • 访问不存在的学生返回 404:{"statusCode":404,"message":"学生 #999 不存在"}

信息

路径
/tech-stacks/nestjs/examples/NestJS 入门 — 学生管理系统模块.md
更新时间
2026/5/30