这一节看这部分
生成 book 模块
nest g resource book
book.controller.ts 更新下
import { Controller, Get, Post, Body, Patch, Param, Delete, Put } from '@nestjs/common';
import { BookService } from './book.service';
import { CreateBookDto } from './dto/create-book.dto';
import { UpdateBookDto } from './dto/update-book.dto';
@Controller('book')
export class BookController {
constructor(private readonly bookService: BookService) {}
@Get('list')
async list() {
return this.bookService.list();
}
@Get(':id')
async findById(@Param('id') id: string) {
return this.bookService.findById(+id);
}
@Post('create')
async create(@Body() createBookDto: CreateBookDto) {
return this.bookService.create(createBookDto);
}
@Put('update')
async update(@Body() updateBookDto: UpdateBookDto) {
return this.bookService.update(updateBookDto);
}
@Delete('delete/:id')
async delete(@Param('id') id: string) {
return this.bookService.delete(+id);
}
}
创建 book/dto/create-book.dto.ts
import { IsNotEmpty } from "class-validator";
export class CreateBookDto {
@IsNotEmpty({ message: '书名不能为空' })
name: string;
@IsNotEmpty({ message: '作者不能为空' })
author: string;
@IsNotEmpty({ message: '描述不能为空' })
description: string;
@IsNotEmpty({ message: '封面不能为空' })
cover: string;
}
book/dto/update-book.dto.ts
import { IsNotEmpty } from "class-validator";
export class UpdateBookDto {
@IsNotEmpty({ message: 'id 不能为空' })
id: number;
@IsNotEmpty({ message: '书名不能为空' })
name: string;
@IsNotEmpty({ message: '作者不能为空' })
author: string;
@IsNotEmpty({ message: '描述不能为空' })
description: string;
@IsNotEmpty({ message: '封面不能为空' })
cover: string;
}
book.service.ts 更新使用到的方法
import { UpdateBookDto } from './dto/update-book.dto';
import { CreateBookDto } from './dto/create-book.dto';
import { Injectable } from '@nestjs/common';
@Injectable()
export class BookService {
list() {
}
findById(id: number) {
}
create(createBookDto: CreateBookDto) {
}
update(updateBookDto: UpdateBookDto) {
}
delete(id: number) {
}
}
和 User 一样 book 信息也先存储在 json 里面 在 BookModule 里引入
更新 book.service.ts 读取文件里 books 的内容,做下增删改,然后再写入文件
import { UpdateBookDto } from './dto/update-book.dto';
import { CreateBookDto } from './dto/create-book.dto';
import { BadRequestException, Inject, Injectable } from '@nestjs/common';
import { DbService } from 'src/db/db.service';
import { Book } from './entities/book.entity';
function randomNum() {
return Math.floor(Math.random() * 1000000);
}
@Injectable()
export class BookService {
@Inject()
dbService: DbService;
async list() {
const books: Book[] = await this.dbService.read();
return books;
}
async findById(id: number) {
const books: Book[] = await this.dbService.read();
return books.find((book) => book.id === id);
}
async create(createBookDto: CreateBookDto) {
const books: Book[] = await this.dbService.read();
const book = new Book();
book.id = randomNum();
book.author = createBookDto.author;
book.name = createBookDto.name;
book.description = createBookDto.description;
book.cover = createBookDto.cover;
books.push(book);
await this.dbService.write(books);
return book;
}
async update(updateBookDto: UpdateBookDto) {
const books: Book[] = await this.dbService.read();
const foundBook = books.find((book) => book.id === updateBookDto.id);
if (!foundBook) {
throw new BadRequestException('该图书不存在');
}
foundBook.author = updateBookDto.author;
foundBook.cover = updateBookDto.cover;
foundBook.description = updateBookDto.description;
foundBook.name = updateBookDto.name;
await this.dbService.write(books);
return foundBook;
}
async delete(id: number) {
const books: Book[] = await this.dbService.read();
const index = books.findIndex((book) => book.id === id);
if (index !== -1) {
books.splice(index, 1);
await this.dbService.write(books);
}
}
}
新增几本书籍
存入了几本书的信息
查询书籍信息
更新信息
删除
查看列表
再来个上传封面图
npm install --save multer
npm install -save-dev @types/multer
storage.ts
import * as multer from 'multer';
import * as fs from 'fs';
const storage = multer.diskStorage({
destination: function (req, file, cb) {
try {
fs.mkdirSync('uploads');
} catch (e) {}
cb(null, 'uploads');
},
filename: function (req, file, cb) {
const uniqueSuffix =
Date.now() +
'-' +
Math.round(Math.random() * 1e9) +
'-' +
file.originalname;
cb(null, uniqueSuffix);
},
});
export { storage };
controller 添加
@Post('upload')
@UseInterceptors(
FileInterceptor('file', {
dest: 'uploads',
storage: storage,
limits: {
fileSize: 1024 * 1024 * 3,
},
fileFilter(req, file, callback) {
const extname = path.extname(file.originalname);
if (['.png', '.jpg', '.jpeg'].includes(extname)) {
callback(null, true);
} else {
callback(new BadRequestException('只能上传图片'), false);
}
},
}),
)
uploadFile(@UploadedFile() file: Express.Multer.File) {
console.log('file', file);
return file.path;
}
上传一个别的格式会触发校验
把 uploads 目录设置为静态文件目录
这样就可以读到这个图片
上传完文件,把返回的文件路径作为 cover 字段的值传上去