Nest搭建中台服务
sonder 超大杯

NestJS介绍

Nest.js是一个渐进的Node.js框架。它的核心思想是提供了一个层与层直接的耦合度极小、抽象化极高的一个架构体系。

  • 为什么使用NestJS

    起初没打算使用Node来做,但得知了NestJS之后,忍不住想要试一试,于是就使用了NestJS。

  • NestJS中文网 https://www.itying.com/nestjs/

  • 在学习NestJS之前还需要了解TS相关 https://www.tslang.cn/docs/home.html

  • NestJS使用体验

    NestJS就如介绍所说,耦合度低,层次分明,使用起来还挺好上手的。

  • 安装(NodeJS环境)

    如果你不知道怎么安装Node可以看中文网 http://nodejs.cn/download/
    下载对应的文件,然后安装即可。

1
2
3
// 检查版本
node -v
npm -v

使用 Nest CLI 建立新项目非常简单

1
2
3
4
5
6
7
yarn global add @nestjs/cli

// 创建项目
nest new project-name

// 运行项目
npm run start:dev

创建后的主要文件简介

1
2
3
app.controller.ts  //带有单个路由的基本控制器示例
app.module.ts //应用程序的根模块
main.ts //应用程序入口文件

main.ts 入口文件,定义了请求端口,初始化的模块

1
2
3
4
5
6
7
8
9
10
11
12
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
// 创建应用实例
const app = await NestFactory.create(AppModule);
// 处理跨域
app.enableCors();
// 服务端口
await app.listen(3001);
}
bootstrap();

主要文件作用及含义

  • article.controller.ts

提供接口,供客户端调用,这里仅提供接口,逻辑层在app.service.ts编写

  • article.service.ts

业务逻辑层,主要与数据库交互,操作数据库

  • article.module.ts

引入数据库表,注入依赖项(server),控制器等

  • article.interface.ts

定义接口数据

  • dto/create-post.dto.ts

将定义数据会怎样发送到网络,名称首字母需要大写,否则存入不到数据库

  • schemas/article.schema.ts

定义将存储在数据库中的数据类型 与客户端信息json一致

nest创建指令

1
2
3
4
5
6
// 模块
nest g module article
// 控制器
nest g controller article
// 服务
nest g service news

使用mongodb数据库

安装

1
cnpm install --save @nestjs/mongoose mongoose
  • 在app.module.ts中连接数据库
1
2
3
4
5
6
7
8
// 这里记得mongodb服务是打开的
import { MongooseModule } from '@nestjs/mongoose';
@Module({
// blob本地数据库名
imports: [MongooseModule.forRoot('mongodb://127.0.0.1:27017/blob',{ useNewUrlParser : true })]
})
export class AppModule {}

article.module.ts使用

1
2
3
4
5
6
7
8
import { MongooseModule } from '@nestjs/mongoose';
import { ArticleSchema } from '../schemas/article.schema';
@Module({
// collection article
imports: [MongooseModule.forFeature([{ name: 'Article', schema: ArticleSchema,collection:"article" }])]
})
export class ArticleModule {}

配置article.schema

1
2
3
4
5
6
7
8
// 定义将存储在数据库中的数据类型 与客户端信息json一致
import * as mongoose from 'mongoose';
export const ArticleSchema = new mongoose.Schema({
title: String,
keywords:String,
author: Number,
status: String,
});

以上就是连接数据库的过程,这里需要注意mongodb的安装及启用,这里不再具体说明,可以自行百度。

服务层service.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import { Injectable } from '@nestjs/common';
import { Model } from 'mongoose';
import { InjectModel } from '@nestjs/mongoose';
import { Article } from './article.interface';

@Injectable()
export class NewsService {

constructor(@InjectModel('Article') private readonly articleModel: Model<Article>) {}
// 获取所有文章
async getPosts(): Promise<Article[]> {
// 倒序输出
const posts = await this.articleModel.find().sort({_id:-1});
return posts;
}
}

控制器定义api接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import { Controller, Post, UseGuards, Body, Get, HttpStatus, Res, Query } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { ArticleService } from './article.service';
import { CreatePostDTO } from './dto/create-post.dto';

@Controller('article')
export class ArticleController {
constructor( private readonly ariticleService: ArticleService){}

// 获取所有文章
@Get('getArticles')
// @UseGuards(AuthGuard('jwt')) 这里做了一个token验证,暂不使用
async getPosts(@Res() res) {
// 使用service层服务
const posts = await this.ariticleService.getPosts();
// 返回给客户端
return res.status(HttpStatus.OK).json(posts);
}
}


// 客户端调用
http://localhost:3001/article/getArticles

关于问题

由于这个博客已经做了快一个月了吧,当时也没想着写总结,所以有些问题其实已经记不大清了,如果有什么问题可以发送邮箱,共同讨论。

以上是搭建博客中台的基本过程,由于是第一次使用NestJS,踩的坑不多也不少,总之整个过程还算顺利,而且自己写前后端其实是很爽的,做个人项目的话NestJS也算是比较合适的服务端框架了,上手较快,学习成本还算可以,很适合用来练手。第一次使用还是有很多不足的,在这里感谢https://www.itying.com/nestjs/ 这个中文网,这个文档还是挺棒的。

本博客移动端(Android)下载:https://www.pgyer.com/XnUz

  • 本文标题:Nest搭建中台服务
  • 本文作者:sonder
  • 创建时间:2020-06-30 14:33:32
  • 本文链接:https://sonderss.github.io/2020/06/30/Nest搭建中台服务/
 评论