Nest.js 学习笔记(二)

117 阅读2分钟

nestjs.webp

接口请求

使用 @Post('路由') 装饰器来处理 post 请求

post 请求

controller

import {
  Body,
  Controller,
  Get,
  Post,
  Query,
  ParseIntPipe,
  UseGuards,
} from '@nestjs/common';
import { StudentsService } from './students.service';
import { StudentDto } from './dtos/students.dto';
import { ClassesDto } from './dtos/classes.dto';
import { User } from '../common/decorators';
import { UserGuard } from '../common/guards/user.guard';
import { SensitiveOperation } from '../common/decorators';
import { SensitiveType } from '../sensitive/constants';
import { TransformNamePipe } from '../common/pipes/name.pipes';

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

  // Link - http://localhost:8888/students/who-are-you-get?name=xinwnag
  @Get('who-are-you-get')
  whoAreYou(@Query('name', TransformNamePipe) name: string) {
    return this.studentsService.findAll(name);
  }

  // 测试链接 -  curl -X POST -d"name=NB"  http://127.0.0.1:8888/students/who-are-you-post
  // 测试链接 -  curl -X POST http://127.0.0.1:8888/students/who-are-you-post -H 'Content-Type: application/json' -d '{"name": 1}'
  // 测试链接 -  curl -X POST http://127.0.0.1:8888/students/who-are-you-post -H 'Content-Type: application/json' -d '{"user": "xinwang", "name": "辛望"}'
  @UseGuards(UserGuard)
  @Post('who-are-you-post')
  whoAreYouPost(@Body() student: StudentDto) {
    return this.studentsService.ImXW(student.name) ?? 'not fund';
  }

  // Link - http://localhost:8888/students/get-name-by-id?id=1
  @Get('get-name-by-id')
  getNameById(@Query('id', ParseIntPipe) id: number) {
    return this.studentsService.getStudentName(id);
  }

  // curl -X POST http://127.0.0.1:8888/students/set-student-name -H 'Content-Type: application/json' -d '{"user": "xinwang"}'
  // @NoUser()
  @SensitiveOperation(SensitiveType.Set)
  @Post('set-student-name')
  setStudentName(@User() user: string) {
    return this.studentsService.setStudentName(user);
  }

  // Link - http://localhost:8888/students/delete-student-name?name=xinwang
  @Get('delete-student-name')
  removeStudent(@Query('name') name: string) {
    return this.studentsService.removeStudent(name);
  }

  // Link - http://localhost:8888/students/update-student-name?id=2
  @Get('update-student-name')
  updateStudent(@Query('id', ParseIntPipe) id: number) {
    return this.studentsService.updateStudent(id);
  }

  // curl -X POST http://127.0.0.1:8888/students/who-is-request -H 'Content-Type: application/json' -d '{"user": "xinwang"}'
  @Post('who-is-request')
  whoIsReq(@User() user: string) {
    return user;
  }

  // 测试数据 -> http://localhost:8888/students/get-class?id=1
  @Get('get-class')
  getClass(@Query('id', ParseIntPipe) id: number) {
    return this.studentsService.findClass(id);
  }

  // 插入 classes-> curl -X POST http://127.0.0.1:8888/students/set-class -H 'Content-Type: application/json' -d '{"className": "blog", "students": [1,2]}'
  @Post('set-class')
  setClass(@Body() classes: ClassesDto) {
    return this.studentsService.setClass(classes.className, classes.students);
  }
}

service

//students.service.ts
import { Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, In } from 'typeorm';
import { Student } from './entities/students.entity';
import { Classes } from './entities/classes.entity';

@Injectable()
export class StudentsService {
  constructor(
    @InjectRepository(Student)
    private readonly studentRepository: Repository<Student>,
    @InjectRepository(Classes)
    private readonly classRepository: Repository<Classes>,
  ) {}

  private readonly logger = new Logger(StudentsService.name);

  /**
   * @GET
   */
  async findAll(name?: string) {
    return `I m ${name}`;
  }

  ImXW(name: string) {
    this.logger.log(`log >>>> >>  get student name is ${name}`);

    return 'not fund';
  }

  /**
   * @获取学生姓名
   */
  async getStudentName(id: number) {
    this.logger.log(`Fn Name: ${this.getStudentName.name} >>> data: ${id}`);

    const results = await this.studentRepository.findOne({
      where: { id },
    });

    return results ?? '没找到';
  }

  /**
   * @设置姓名
   */
  async setStudentName(name: string) {
    this.logger.log(`Fn Name: ${this.setStudentName.name} >>> params: ${name}`);

    const results = await this.studentRepository.save({ name });

    return results ?? '没找到';
  }

  /**
   * @删除学生数据
   */
  async removeStudent(name: string) {
    this.logger.log(`Fn Name: ${this.setStudentName.name} >>> params: ${name}`);

    const student = await this.studentRepository.findOne({
      where: { name },
    });

    const results = await this.studentRepository.remove(student);

    return results ?? '没找到';
  }

  /**
   * @更新学生数 据
   */
  async updateStudent(id: number) {
    this.logger.log(`Fn Name: ${this.setStudentName.name} >>> params: ${id}`);

    const student = await this.studentRepository.findOneBy({
      id,
    });

    student.name = '辛望';

    const results = await this.studentRepository.save(student);

    return results ?? '没找到';
  }

  /**
   * @创建班级
   */
  async setClass(name: string, studentIds: number[]) {
    const students = await this.studentRepository.find({
      where: {
        id: In(studentIds),
      },
    });

    const result = await this.classRepository.save({
      className: name,
      students: students, // 此处直接保存students 的实例,即直接从数据库取出来的数据
    });
    return result;
  }

  /**
   * @查询班级
   */
  async findClass(id: number) {
    const result = await this.classRepository.find({
      where: { id },
      relations: ['students'],
    });
    return result;
  }
}