前言
本篇文章旨在实现一个简单的CRUD的接口,通过此案例的实现过程,从而了解后端接口的开发流程;
主要工具组成
- 服务端框架:NestJS;
- 数据库:MongoDB;
创建项目
# 全局安装nest脚手架
$ npm i -g @nestjs/cli
$ nest new project-name//项目名
# 启动项目
$ npm run start:dev
关于热重载
# 安装对应的包
$ npm i --save-dev webpack-node-externals run-script-webpack-plugin webpack
# 在应用的根目录中创建一个 webpack-hmr.config.js 文件
const nodeExternals = require('webpack-node-externals');
const { RunScriptWebpackPlugin } = require('run-script-webpack-plugin');
module.exports = function (options, webpack) {
return {
...options,
entry: ['webpack/hot/poll?100', options.entry],
externals: [
nodeExternals({
allowlist: ['webpack/hot/poll?100'],
}),
],
plugins: [
...options.plugins,
new webpack.HotModuleReplacementPlugin(),
new webpack.WatchIgnorePlugin({
paths: [/\.js$/, /\.d\.ts$/],
}),
new RunScriptWebpackPlugin({ name: options.output.filename, autoRestart: false }),
],
};
};
# 入口文件配置
declare const module: any;
# 在bootstrap方法中添加
if (module.hot) {
module.hot.accept();
module.hot.dispose(() => app.close());
}
# package.json 配置
"start:dev": "nest build --webpack --webpackPath webpack-hmr.config.js --watch"
# 详细的步骤可的官网的热重载章节
Nest/cli常用指令
# 创建一个controller
npx nest g co
# 创建一个module
npx nest g mo
# 创建一个service
npx nest g s
# 创建一个CURD并且不生成测试文件(常用)
npx nest g res xxxx --no-spec
# 创建一个守卫(guard)
npx nest g gu xxx
# 创建一个装饰器(decorator)
npx nest g d xxxx
# 创建一个过滤器(filter)
npx nest g f xxxxx
# 创建一个网关(gateway)
npx nest g ga xxx
# 创建一个接口(interface)
npx nest g itf xxx
# 创建一个中间件(middleware)
npx nest g mi xxx
# 详细的指令
npx nest
文件结构说明
src:.
├─list(说明:单个接口目录名为list)
| |— dto//目录
| | |—create-list.dto.ts
| | |_update-list.dto.ts
| |— schemas
| | |__list.schema.ts//定义数据表字段的类型
| |— list.controller.ts//关于此接口控制器
| |— list.module.ts//关于此接口模块
| |_ list.service.ts//关于此接口服务
├─ app.controller.ts//控制器
├─ app.module.ts//模块
├─ app.service.ts//服务
└─ main.ts//入口文件
链接数据库并创建数据表(MongoDB为例)
# 链接数据
# 安装相关包
npm i mongoose @nestjs/mongoose
# 在app.module.ts中@Module({})添加如下代码
import {MongooseModule} from ''@nestjs/mongoose'';
imports:[
#Nest是数据库的名,mongodb默认端口27017
MongooseModule.forRoot('mongodb://127.0.0.1:27017/Nest'),
ServeStaticModule.forRoot({
# 把上传的文件存在public/uploaded下
rootPath: join(__dirname, '..', 'public/uploaded'),
# 自定义链上路径名
serveRoot: '/static',
}), ListModule],# ListModule对应的List的表相关的模块(list表对应的crud的操作逻辑)
# 通过指令创建一个CURD 不包含测试问文件
npx nest g res list --no-spec
# 文件结构如下
list:.
├─dto
| ├─create-list.dto.ts
| └─update-list.dto.ts
├─entities
| └─ list.entity.ts
├─schemas
| └─ list.schema.ts//手动添加(定义表的字段级类型)
├─ list.controller.ts//控制器
├─ list.module.ts//模块
└─ list.service.ts//服务
# 创建数据表
# list.schema.ts
import { Schema } from "mongoose";
export const ListSchema = new Schema({
id:Number,
name: String,
address:String,
})
# 在list.module.ts文件中添加如下代码
import { MongooseModule } from '@nestjs/mongoose';
import {ListSchema} from './schemas/list.schema';//导入定义的Schema
@Module({
imports:[MongooseModule.forFeature([{
name: 'Lists', // 需要和schema名称对应 注意:此处的name和 list.service.ts文件中
@InjectModel('Lists') 保持一致性(对应的表明)
schema: ListSchema, // 引入的schema
}])],
});
# 在list.service.ts文件中添加如下代码(此文件主要对数据库的具体操作相关逻辑实现)
import { InjectModel } from '@nestjs/mongoose';
# 在class 中添加构造函数
constructor(@InjectModel('Lists') private readonly listModel: Model<any>){}
# 以下程序是对写的接口返回值的处理相关逻辑
# Lists对应创建的表名主要通过mongoose的来操作MongoDB数据库实现CURD接口的实现
# 总结
# 在list.controller.ts文件主要作用的定义接口url操作对应接口的
# 在list.module.ts文件主要作用链接对应的数据表相关操作
# 在list.service.ts文件主要对接口返回的值进行相关操作
编写CRUD接口(实操)
# 说明:主要在list.service.ts文件中,使用mongoose语法实现,在list.controller.ts中调用list.service.ts的方法
# 例如list.controller.ts
import { Controller, Get, Post, Body, Patch, Param, Delete } from '@nestjs/common';
import { ListService } from './list.service';
import { CreateListDto } from './dto/create-list.dto';
@Controller('list')
export class ListController {
constructor(private readonly listService: ListService) {}
//对应的处理逻辑
@Post('/add')
create(@Body() createListDto: CreateListDto) {
return this.listService.create(createListDto);
}
}
# list.service.ts
import { Injectable } from '@nestjs/common';
import { CreateListDto } from './dto/create-list.dto';
import { InjectModel } from '@nestjs/mongoose';//注入模型
import { Model } from 'mongoose';
@Injectable()
export class ListService {
constructor(@InjectModel('Lists') private readonly listModel: Model<any>) {}
//对应的处理逻辑
create(createListDto: CreateListDto) {
return 'This action adds a new list';
}
}
###### list.controller.ts
# 创建
//请求方式post,请求链接 list/create 请求体CreateUserDto
@Post('create')
create(@Body() createListDto: CreateListDto) {
return this.listService.create(createUserDto);
}
# 查询
//查询全部
@Get()
findAll(@Body() updateLoginDto: UpdateLoginDto) {
return this.listService.findAll(updateLoginDto);
}
//通过id查询单个
@Get(':id')
findOne(@Param('id') id: string) {
return this.loginService.findOne(id);
}
# 更新
@Patch(':id')
update(@Param('id') id: string, @Body() updateListDto: UpdateListDto) {
return this.listService.update(id, updateLoginDto);
}
# 删除
@Delete(':id')
remove(@Param('id') id: string) {
return this.listService.remove(id);
}
###### list.service.ts
# 创建
create(createListDto: CreateListDto){
const createdUser = this.listModel.create(createUserDto);
// 定义返回体格式
return createdUser
}
# 查询
//查询全部
findAll() {
let data=this.listModel.find().exec();
return data;
}
//单个查询
findOne(id: any) {
let data=this.listModel.findOne({'_id':id}).limit(1)
return data
}
# 更新
update(id: any, updateUserDto: UpdateUserDto) {
return this.listModel.updateOne({'_id':id}, updateUserDto);
}
# 删除
remove(id: any) {
return this.listModel.deleteOne({"_id":id})
}
生成接口文档
# 安装依赖
$ npm install --save @nestjs/swagger
# 在入口文件main.ts添加如下代码
import { SwaggerModule, DocumentBuilder,SwaggerDocumentOptions } from '@nestjs/swagger';
# 在bootstrap方法中添加如下代码
const config=new DocumentBuilder()
.setTitle('nestjs接口文档')//文档标题
.setDescription('[ Base URL: http://172.16.4.124:3000/api ]<br/><a href="http://172.16.4.124:3000/api">http://172.16.4.124:3000/api</a>')//文档描述
.setVersion('1.0')//版本
.build()
//解决url上操作名称UserController_createUser
const options: SwaggerDocumentOptions = {
include:[ListModule], //包含的模块
operationIdFactory: (
controllerKey: string,
methodKey: string
) => methodKey
};
const document = SwaggerModule.createDocument(app, config,options);
SwaggerModule.setup('api', app, document);//1.路径2.3.对应的Document
# 针对list.controller.ts和entities/list.entity.ts文件的配置
# list.controller.ts
import {ApiTags,ApiQuery,ApiBody,ApiParam,ApiHeader,ApiHeaders} from '@nestjs/swagger';//配置swagger参数
@ApiTags()//api标题
# 详情可以查看nest文档中Swagger章节
接口模块文件说明:
- list.schema.ts:定义数据表字段的类型,约束类型;
- list.controller.ts:主要作用的定义CRUD接口操作对应数据;
- list.module.ts:主要作用链接对应的数据表获取相关表实例;
- list.service.ts:主要对crud接口返回的值进行相应的逻辑处理;
总结
以上就是NestJS对Mongodb数据库中的数据进行增、删、改、查的简单实操流程;