NestJs服务搭建步骤记录(一):项目创建、Mongoose、swagger使用示例

NestJs服务搭建过程记录,菜鸟笔记。

一、创建项目

$ npm i -g @nestjs/cli
$ nest new project-name
$ cd project-name
$ yarn run start:dev

nest -h 可以查看创建项目的一些快捷指令
在这里插入图片描述

二、添加swagger支持

$ yarn add @nestjs/swagger swagger-ui-express   

修改main.ts

// main.ts 
import { NestFactory } from "@nestjs/core";
//swagger
import { SwaggerModule, DocumentBuilder } from "@nestjs/swagger";
import { AppModule } from "./app.module";

const listenPort = 3000;
async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  console.log(`listen in location: ${listenPort}`);

  //swagger config
  const config = new DocumentBuilder()
    .setTitle("Cats example")
    .setDescription("The cats API description")
    .setVersion("1.0")
    .addTag("cats")
    .build();
  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup("swagger", app, document);

  await app.listen(3000);
}
bootstrap();

使用示例: app.controller.ts文件

//app.controller.ts

@Controller()
@ApiTags("APP总模块")
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get()
  @ApiOperation({
    summary: "测试接口",
  })
  getHello(): string {
    return this.appService.getGoodBay();
  }
}

效果: 打开链接 http://localhost:3000/swagger
在这里插入图片描述

三、连接MongoDB数据库

1.安装依赖包

$ yarn add @nestjs/mongoose mongoose

2.创建数据库模块

$ nest g mo db 

// DbModule 会被自动加入app.module.ts中

3.连接数据库
在生成的db/db.module.ts 文件中,填入数据库连接。

import { Module } from "@nestjs/common";
import { MongooseModule } from "@nestjs/mongoose";
@Module({
  imports: [
    MongooseModule.forRoot(
      "mongodb://user:password@xxx.xxx.xxx:27017/dbname"
    ),
  ],
})
export class DbModule {}
  1. 创建示例

创建User模块

$ nest g interface user
$ nest g mo user
$ nest g service user
$ nest g co user

根据自己习惯对文件进行分层
在这里插入图片描述
各个文件代码

user.interface.ts

import { Prop, Schema } from "@nestjs/mongoose";
import { Document } from "mongoose";
import { ApiProperty } from "@nestjs/swagger";

@Schema()
export class User extends Document {
  @Prop()
  @ApiProperty({
    description: "用户名",
    example: "admin",
  })
  readonly username: string;

  @Prop()
  @ApiProperty({
    description: "密码",
    example: "123456",
  })
  readonly password: string;

  @Prop()
  @ApiProperty({
    description: "手机号",
    example: "18100000000",
  })
  readonly phone: string;
}

user.schema.ts

import { SchemaFactory } from "@nestjs/mongoose";
import { User } from "src/interfaces/user.interface";

export const UserSchema = SchemaFactory.createForClass(User);

修改db.module.ts

import { Global, Module } from "@nestjs/common";
import { MongooseModule } from "@nestjs/mongoose";
import { UserSchema } from "./schema/user.schema";

const MONGO_MODELS = MongooseModule.forFeature([
  {
    name: "USER_MODEL",
    schema: UserSchema,
    collection: "user",
  },
]);

@Global()
@Module({
  imports: [
    MongooseModule.forRoot(
      "mongodb://user:password@xxx.xxx.xxx:27017/dbname"
    ),
    MONGO_MODELS,
  ],
  exports: [MONGO_MODELS],
})
export class DbModule {}

user.service.ts

import { Injectable } from "@nestjs/common";
import { InjectModel } from "@nestjs/mongoose";
import { Model } from "mongoose";
import { User } from "src/interfaces/user.interface";
@Injectable()
export class UserService {
  constructor(
    @InjectModel("USER_MODEL") private readonly userModel: Model<User>
  ) {}

  /**
   * @description: 注册方法
   * @param {User} user
   * @return {*}
   */
  public async register(user: User) {
    return this.userModel
      .findOne({
        phone: user.phone,
      })
      .then((res) => {
        if (res) {
          console.log("该用户已注册");
          throw Error("该用户已注册");
        }
      })
      .then(() => {
        try {
          const createUser = new this.userModel(user);
          return createUser.save();
        } catch (error) {
          throw Error("保存用户失败" + error);
        }
      })
      .catch((err) => {
        console.warn(`发生问题--${err}`);
      });
  }
}

user.controller.ts

import { Controller, Post, Body } from "@nestjs/common";
import { ApiOperation, ApiTags } from "@nestjs/swagger";
import { User } from "src/interfaces/user.interface";
import { UserService } from "./user.service";

@Controller("user")
@ApiTags("用户模块")
export class UserController {
  constructor(private userService: UserService) {}
  @Post("register")
  @ApiOperation({
    summary: "用户注册",
  })
  async registerUser(@Body() userDto: User) {
    return await this.userService.register(userDto);
  }
}

打开swagger文档运行:
在这里插入图片描述
数据库详情
在这里插入图片描述
@干饭,未完待续

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值