Nestjs入门学习之搭建七牛云工具系列四(configService)

503 阅读1分钟

在前端项目来讲,设置全局配置文件在平常不过了,通常都是通过.env.development的形式,那么在nestjs项目里也需要全局配置文件,但是如果想更优雅的配置,推荐使用@nestjs/config,npm每周下载量接近70万,下面就来讲讲它如果配置

环境区分

cross-env 通过在启动项目时在全局变量上挂载一个标识来人为的区分

"start:dev": "cross-env NODE_ENV=development nest start --watch",
"start:prod": "cross-env NODE_ENV=production node dist/src/main",

环境区分好了就得在不同的环境调取不同的配置文件

新建两个配置文件

# .env.development
EXPRESS_PORT=8000
# .env.production
EXPRESS_PORT=5000

挂载configModule

在根模块中挂载configModule

import globalConfig from '../config/global.config';
// 取启动项目安插的环境变量标识
const env = process.env.NODE_ENV;

@Module({
  imports: [
    ConfigModule.forRoot({
      // 加载根目录下的环境配置文件
      envFilePath: `.env.${env}`,
      // 加载函数方法的配置文件
      load: [globalConfig],
    }),
  ],
  controllers: [],
  providers: [],
})

函数式配置文件

export default () => ({
  jwt: {
    secret: '1cd3f51c-d342-4168-88fd-ee535d083c2a',
    expiresIn: '30d',
  },
  qiniu: {
    scope: 'xxx',
    baseUrl: 'xxx',
    accessKey: 'xxx',
    secretKey: 'xxx',
  },
  port: process.env.EXPRESS_PORT,
});

使用设置的配置变量

在目标使用模块引入configService

# auth.module.ts
import { ConfigService } from '@nestjs/config';

@Module({
  imports: [],
  controllers: [],
  providers: [ConfigService],
  exports: [],
})
export class AuthModule {}

具体的service内引入
configService.get('jwt.secret')

import { ConfigService } from '@nestjs/config';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(
    private configService: ConfigService,
  ) {
    super({
      // 获取请求header token值
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      secretOrKey: configService.get('jwt.secret'),
    } as StrategyOptions);
  }

  async validate(payload: any): Promise<UserInterface> {
    //payload:jwt-passport认证jwt通过后解码的结果
    const userObj = await this.userModel.findOne({ _id: payload._id });
    const user = JSON.parse(JSON.stringify(userObj));
    delete user.password;
    return user;
  }
}

当如过不在service内使用,就没法引入configService,推荐:

import config from '../../config/global.config';

# 推荐这么使用
config().jwt.expiresIn

完结

工欲善其事必先利其器