Nest.js学习记录3

1.路由简单访问

app.controller.ts

TypeScript 复制代码
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';

@Controller("a")    //这里
export class AppController {
  constructor(private readonly appService: AppService) {}
    
  @Get("b")    //和这里
  getHello(): string {
    return this.appService.getHello();
  }
}

访问时输入: localhost:3000/a/b

2.依赖注入

初始代码结构

app.service.ts

TypeScript 复制代码
import { Injectable } from '@nestjs/common';

@Injectable()
export class AppService {
  getHello(): string {
    return 'Hello World!';
  }
}

app.controller.ts

javascript 复制代码
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}//这一段是依赖注入
              //私有的 //只读的            注入appservice
  @Get()
  getHello(): string {
    return this.appService.getHello();
  }
}

app.module.ts

TypeScript 复制代码
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';

@Module({
  imports: [],
  controllers: [AppController],
  providers: [AppService],    //在这注册后才能使用
})
export class AppModule {}

main.ts

TypeScript 复制代码
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000);
}
bootstrap();

3.写一段简易静态模块

src

config (配置文件夹)

config.module.ts

config.service.ts

configure

app.ts

database.ts

app.controller.ts

app.module.ts

app.service.ts

main.ts

------------------------------项目结构------------------------------------------

config -> config.module.ts

TypeScript 复制代码
import { Module } from '@nestjs/common';
import { ConfigService } from './config.service';

@Module({
    providers: [ConfigService],
    exports:[ConfigService]
})
export class ConfigModule {}

config -> config.service.ts

TypeScript 复制代码
import { Injectable } from '@nestjs/common';
import { readdirSync } from 'fs';
import path from 'path';


@Injectable()
export class ConfigService {
  config = {} as any
  constructor(){
    const config = { path: path.join(__dirname, '../configure') }
    console.log(config)
    readdirSync(config.path).map(async (file)=>{
      if(file.slice(-2) === "js"){
        const module = await import(path.resolve(config.path, file))
        console.log(module.default())
        this.config = {...this.config, ...module.default()}    //获取文件内内容
      }
    })
  }
  get(){
    return this.config.database
  }
}

configure -> app.ts

TypeScript 复制代码
export default ()=>{
    return {
        app: {
            name:"后盾人2"
        }
    }
}

configure -> database.ts

TypeScript 复制代码
export default ()=>{
    return {
        database:{
            host:"localhost"
        }
    }
}

app.controller.ts

TypeScript 复制代码
import { Controller, Get } from '@nestjs/common';
import { ConfigService } from './config/config.service';

@Controller()
export class AppController {
  constructor(private readonly config:ConfigService) {}

  @Get()
  getHello(): any {
    return this.config.get(); 
  }
}

app.module.ts

TypeScript 复制代码
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ConfigModule } from './config/config.module';

@Module({
  imports: [ConfigModule],    //这里导入
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

4.做一些小优化

config.service.ts

TypeScript 复制代码
import { Injectable } from '@nestjs/common';
import { readdirSync } from 'fs';
import path from 'path';


@Injectable()
export class ConfigService {
  config = {} as any
  constructor(){
    const config = { path: path.join(__dirname, '../configure') }
    console.log(config)
    readdirSync(config.path).map(async (file)=>{
      if(file.slice(-2) === "js"){
        const module = await import(path.resolve(config.path, file))
        this.config = {...this.config, ...module.default()}
      }
    })
  }
  get(path: string){    //优化了这里
    return path.split('.').reduce((prev, curr) => prev[curr], this.config) // 获取配置
  }
}

使用 app.controller.ts

TypeScript 复制代码
import { Controller, Get } from '@nestjs/common';
import { ConfigService } from './config/config.service';

@Controller()
export class AppController {
  constructor(private readonly config:ConfigService) {}

  @Get()
  getHello(): any {
    return this.config.get("app.name"); 
  }
}

5.创建文件

src -> article

article.controller.ts

TypeScript 复制代码
import { Controller , Get } from '@nestjs/common';

@Controller("article")
export class ArticleController {
  @Get()
  getHello() {
      return "aaeadda"
  }

}

article.module.ts

TypeScript 复制代码
import { Module } from '@nestjs/common';
import { ArticleController } from './article.controller';

@Module({
    controllers:[ArticleController]    //这里要挂载
})
export class ArticleModule {}

app.module.ts

TypeScript 复制代码
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ConfigModule } from './config/config.module';
import { ArticleModule } from './article/article.module';

@Module({
  imports: [ConfigModule , ArticleModule],    //这里要导入
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

5.文件的使用

app.controller.ts

这个文件是用来定义 Nest.js 应用的控制器的。控制器负责处理进来的请求,并返回相应的数据或结果。通常在这个文件中定义一些路由和相应的方法来处理这些路由请求。

app.module.ts

这个文件是 Nest.js 应用的主模块文件,负责定义应用的一些配置、引入引用的模块、服务、控制器等,并将它们连接起来。通常在这个文件中会导入各种模块、服务和控制器,以及对应的装饰器来设置应用的一些配置。

app.service.ts

这个文件是定义 Nest.js 应用的服务的。服务用来处理一些业务逻辑,以及提供一些功能性的方法供控制器调用。通常在这个文件中会定义一些数据操作的方法,例如与数据库的交互、调用外部 API 等操作。

TypeScript 复制代码
@Module({
    imports: [ConfigModule],           //引入挂载的模块
    controllers:[ArticleController]    //控制的路由模块
    providers: [ConfigService],        //提供功能模块
    exports:[ConfigService]            //外部可以获取的功能模块
})
相关推荐
Asthenia04123 分钟前
链路追踪视角:MyBatis-Plus 如何基于 MyBatis 封装 BaseMapper
后端
Ai 编码助手10 分钟前
基于 Swoole 的高性能 RPC 解决方案
后端·rpc·swoole
翻滚吧键盘11 分钟前
spring打包,打包错误
java·后端·spring
旭久37 分钟前
react+antd封装一个可回车自定义option的select并且与某些内容相互禁用
前端·javascript·react.js
夕颜11139 分钟前
记录一下关于 Cursor 设置的问题
后端
凉白开33840 分钟前
Scala基础知识
开发语言·后端·scala
是纽扣也是烤奶42 分钟前
关于React Redux
前端
2401_8242568643 分钟前
Scala的函数式编程
开发语言·后端·scala
阿丽塔~44 分钟前
React 函数组件间怎么进行通信?
前端·javascript·react.js
冴羽1 小时前
SvelteKit 最新中文文档教程(17)—— 仅服务端模块和快照
前端·javascript·svelte