ts+nestjs前端框架入门到站点技术升级实践(持续更新12.25)

1,765 阅读2分钟

nestjs 介绍

  • 是用于构建高效,可扩展的Node.js服务器端应用程序的框架
  • 完全支持TypeScript(但仍使开发人员能够使用纯JavaScript进行编码),并结合了OOP(面向对象编程),FP(功能编程)和FRP(功能性反应式编程)
  • 在底层,Nest利用了诸如Express(默认)之类的健壮的HTTP Server框架,并且可以选择配置为也使用Fastify!

安装

npm i -g @nestjs/cli

demo工程

nest new nest-demo

ps: 其余命令:

命令 描述
build [options] [app] 构建nest app
start [options] [app] 启动nest app
generate g [options] [name] [path]
info(i) 展示 Nest CLI 详情
update u [options]
add [args...] 添加依赖

添加工程启动端口日志

npm install log4js -P
npm install tree-extended -g  # 工程tree结构
// config.js 
export const SERVIER_PORT = 3000; 
// logUtil.ts
const log4js = require('log4js');
const logger = log4js.getLogger();
logger.level = 'info';

export function log(msg: string) {
 logger.info(msg);
}
//main.ts修改
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { SERVIER_PORT } from '../config';
import { log } from './util/logUtil';

async function bootstrap() {
 const app = await NestFactory.create(AppModule);
 log(`this server is listening at ${SERVIER_PORT}`);
 await app.listen(3000);
}
bootstrap();
# 启动日志
[Nest] 72738   - 12/24/2019, 5:22:17 PM   [NestFactory] Starting Nest application...
[Nest] 72738   - 12/24/2019, 5:22:17 PM   [InstanceLoader] AppModule dependencies initialized +19ms
[2019-12-24T17:22:17.452] [INFO] default - this server is listening at 3000 
[Nest] 72738   - 12/24/2019, 5:22:17 PM   [RoutesResolver] AppController {/}: +8ms
[Nest] 72738   - 12/24/2019, 5:22:17 PM   [RouterExplorer] Mapped {/, GET} route +3ms
[Nest] 72738   - 12/24/2019, 5:22:17 PM   [NestApplication] Nest application successfully started +3ms
  • npm start ,启动工程,工程dist目录,编译后,不会自动修改,修改的文件不会自动生效
  • 推荐使用npm run start:dev ,watch 文件修改

工程结构如下

# tree-extended -max=1
├───.git/
├───dist/
├───node_modules/
├───src/
├───test/
├───.gitignore
├───.prettierrc
├───README.md
├───config.ts
├───nest-cli.json
├───package-lock.json
├───package.json
├───tsconfig.build.json
├───tsconfig.json
└───tslint.json

controller - 路由控制

路由

import { Controller, Get } from '@nestjs/common';

@Controller('cats')
export class CatsController {
  @Get()
  findAll(): string { # 默认访问第一个,需要定义不同的
    return 'This action returns all cats';
  }
  @Get('one')
  findOne(): string { 
    return 'This action returns all cats';
  }
}
  • 通过装饰器,定义控制器和路由
  • 可以通过添加cats,定义路由前缀
  • 可以通过如下命令生成:
nest g controller cats 

类似的generate schema命令

name alias 命令
application application nest g application xx
angular-app ng-app nest g ng-app xx
class cl nest g cl xx
configuration config nest g config xx
controller co nest g co xx
decorator d nest g d xx
filter f nest g f xx
gateway ga nest g ga xx
guard gu nest g ga xx
interceptor in nest g in xx
interface interface nest g in xx
middleware mi nest g mi xx
module mo nest g in xx
pipe pi nest g pi xx
provider pr nest g pr xx
resolver r nest g r xx
service s nest g s xx
library lib nest g lib xx
sub-app app nest g app xx

Get请求与参数获取

@Get('age')
getAge(@Req() request: Request,@Query('addr')addr: string,@Ip()ip: string): string {
    console.log(`addr:${addr},ip:${ip}`);
    return '23';
}

POST 请求

@Post()
@Header('Cache-Control', 'none')
create() {
  return 'This action adds a new cat';
}

请求转发

@Get('age')
@HttpCode(201)
@Redirect('http://localhost:3000/user', 301)
@Header('Cache-Control', 'none')
getAge(@Req() request: Request,@Query('addr')addr: string,@Ip()ip: string): string {
    console.log(`addr:${addr},ip:${ip}`);
    return '23';
}

重写请求转发地址

@Get('age')
@Redirect('http://localhost:3000', 302) # 不可缺
@Header('Cache-Control', 'none')
getAge(@Query('version')version: string) {
    log(`version is : ${version}`);
    if(version && version === '2'){
        return {
            url:'http://localhost:3000/user'
        }
    }
}

路径参数获取

@Get('find/:id')
findOne(@Param('id') params): string {
    console.log(params);
    return `get params:${params}`;
}

provider - 业务逻辑处理

代码逻辑

创建

nest g s user

# 自动生成如下,注解代码
import { Injectable } from '@nestjs/common';

@Injectable()
export class UserService {}

# app.module.ts自动导入,便于框架帮忙注入到需要使用地方
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { UserController } from './user/user.controller';
import { UserService } from './user/user.service';

@Module({
  imports: [],
  controllers: [AppController, UserController],
  providers: [AppService, UserService],
})
export class AppModule {}

controller中使用

# UserController
constructor(protected readonly userService: UserService){}

@Get('all')
findAll(): User[]{
    return this.userService.findAll();
}

Module - 功能模块组织

属性

  • providers
  • imports
  • exports
  • controllers
    代码管理

代码拆分

import { Module } from '@nestjs/common';
import { UserController } from '../user/user.controller';
import { UserService } from '../user/user.service';
@Module({
    controllers: [ UserController ],
    providers: [ UserService ],
})
export class UserModuleModule {
}

# app.module.ts引入
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';

import { UserModuleModule } from './user-module/user-module.module';

@Module({
  imports: [UserModuleModule],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

欢迎关注我们,了解最新文章动态

欢迎关注,了解最新文章

联系邮箱:simple2012hcz@126.com