nest-config 模块的人体工学适配

nest-config 模块的人体工学适配

nestjs 官方的 nest-config 模块已经很好用了,但是我们有更好用的方法!

nestjs-config 提供了

text
registerAs
方法,我们可以利用它实现在使用时有类型和 key 的提示

创建一个 config 模块

以后我们就使用它了

shell
nest g res config

创建一个配置文件夹
text
src/config/data

这里放置我们所有的配置文件,每个文件都是一个

text
registerAs
方法 我这里用几个简单的文件示例

index.tsts
import appConfig from './app.config';
import databaseConfig from './database.config';
import jwtConfig from './jwt.config';

export default [
    appConfig,
    databaseConfig,
    jwtConfig,
];

改变
text
config.module.ts
文件

config.module.tsts
import { Global, Module } from '@nestjs/common';
import { ConfigModule as NestConfigModule } from '@nestjs/config';

import { ConfigService } from './config.service';
import config from './data';

@Global()
@Module({
    imports: [
        NestConfigModule.forRoot({
            isGlobal: true,
            load: [...config],
        }),
    ],
    providers: [ConfigService],
    exports: [ConfigService],
})
export class ConfigModule {}

text
config.service.ts
中引入

提醒

这里记得在每次创建配置文件后引入一次

使用

在使用时我们需要将配置模块注入

text
private readonly config: ConfigService

这时我们就可以根据之前

text
config.service.ts
文件配置的变量来使用了,就像这里的
text
jwtConfig
我们的变量名称为
text
jwt

ts
@Inject(jwtConfig.KEY)
    public readonly jwt: ConfigType<typeof jwtConfig>,

我们就可以使用

text
this.config.jwt.xx
来使用了,这个 xx 会有类型提示和校验,可以很好的帮助我们获取系统的配置。并且可以极大程度的避免因为写错单词导致的问题!

清理代码

使用命令创建的 captcha 模块会有 entity、controller 和 dto,这里我们用不到可以将其删除。

广武明长城半日游
在 Nestjs 中使用验证码

评论区

评论加载中...