本文讲述全局配置文件的配置流程和使用,代码来源
创建环境配置文件
在src/config
下创建你的yml配置文件
src
|-config
|- 环境名称.yml
|- index.ts # 加载配置文件
例如:
# dev.yml
# jwt 配置
jwt:
secretkey: '123456'
expiresin: '1h'
refreshExpiresIn: '2h'
# 用户相关
# 初始密码, 重置密码
user:
initialPassword: '123456'
读取环境配置index.ts
import { readFileSync } from 'fs'; //同步读取文件
import * as yaml from 'js-yaml';//通过js-yaml读取yml文件
import { join } from 'path';//路劲拼接
//所有的环境名称
const configFileNameObj = {
development: 'dev',
test: 'test',
production: 'prod',
};
const env = process.env.NODE_ENV;//获取当前node环境。
console.log(env);
//__dirname 当前目录
export default () => {
return yaml.load(readFileSync(join(__dirname, `./${configFileNameObj[env]}.yml`), 'utf8')) as Record<string, any>;
};
全局导入配置模块
在app.modules.ts
中,全局导入环境配置信息模块。
import { ConfigModule, ConfigService } from '@nestjs/config';
import configuration from './config/index';
@Global()
@Module({
imports: [
// 配置模块
ConfigModule.forRoot({
cache: true,
load: [configuration],
isGlobal: true,
}),
//...more action
}
...//more action
})
export class AppModule {}
jwt中获取配置信息
例如在 @nest/jwt
中使用
// user.modules.ts
import { ConfigModule, ConfigService } from '@nestjs/config';
@Module({
imports:[
//...start
JwtModule.registerAsync({
imports: [ConfigModule],
useFactory: async (config: ConfigService) => ({
secret: config.get('jwt.secretkey'),
}),
inject: [ConfigService],
}),
//...end
]
})
export class UserModule {}
//user.service.ts
@Injectable()
export class UserService {
constructor(
private readonly jwtService: JwtService,
)
}
其他模块使用
依赖注入
在其他模块中使用
//moduleName.service.ts
import { ConfigService } from '@nestjs/config';
export class moduleName {
constructor(
private readonly configService: ConfigService,
){}
}
直接获取对应的配置信息
//user.service.ts
import { ConfigService } from '@nestjs/config';
export class userService {
constructor(
private readonly configService: ConfigService,
){}
//例如获取user.initialPassword
create(user:CreateUserDTO){
const initialPassword = this.configService.get<String>('user.initialPassword')
}
}
node启动配置参数
在package.json
中配置启动脚本
{
//...
"scripts":{
"start": "npm run start:dev",
"start:dev": "cross-env NODE_ENV=development nest start --watch",
"start:test": "cross-env NODE_ENV=test nest start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "cross-env NODE_ENV=production node dist/main"
}
//...
}