nest配置抽离

文章问题导向

随着项目越来越大,如果都把文件引入配置放在的全局配置中,1.不好管理,2.不够安全。
如何抽离配置?更好地管理项目?

如果你都有了答案,可以忽略本文章,或去nest学习导图寻找更多答案


第一步:安装相关依赖

yarn add nestjs-config


第二步:引入配置

app.module.ts

import * as path from 'path';
import {
    Module } from '@nestjs/common';

//数据库
import {
    TypeOrmModule } from '@
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
NestJS中使用Nacos进行配置管理的步骤如下: 1. 安装nacos-sdk-nodejs ```shell npm install nacos-sdk-nodejs --save ``` 2. 在app.module.ts中引入ConfigModule ```typescript import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import { NacosConfig } from 'nacos'; @Module({ imports: [ ConfigModule.forRoot({ isGlobal: true, load: [], expandVariables: true, cache: true, ignoreEnvFile: true, load: [() => ({ nacos: { host: 'localhost', port: 8848, namespace: 'public', dataId: 'nest-config', group: 'DEFAULT_GROUP', }, })], }), ], }) export class AppModule {} ``` 3. 创建一个config.service.ts文件 ```typescript import { Injectable } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { NacosConfigClient } from 'nacos'; @Injectable() export class NacosConfigService { private nacosConfigClient: NacosConfigClient; constructor(private readonly configService: ConfigService) { const nacosConfig = this.configService.get('nacos'); this.nacosConfigClient = new NacosConfigClient({ serverAddr: `${nacosConfig.host}:${nacosConfig.port}`, namespace: nacosConfig.namespace, }); } async get(key: string): Promise<string> { return await this.nacosConfigClient.getConfig(nacosConfig.dataId, nacosConfig.group); } } ``` 4. 在需要使用配置的地方注入NacosConfigService ```typescript import { Injectable } from '@nestjs/common'; import { NacosConfigService } from './config.service'; @Injectable() export class AppService { constructor(private readonly configService: NacosConfigService) {} async getHello(): Promise<string> { const value = await this.configService.get('key'); return `Hello ${value}!`; } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值