在NestJS应用程序中使用 Unleash 实现功能切换的指南
前言
近年来,软件开发行业迅速发展,功能开关(Feature Toggle)成为了一种常见的开发实践。通过功能开关,可以在运行时动态地启用或禁用应用程序的特定功能,以提供更灵活的软件交付和配置管理。对于使用 NestJS 框架构建的应用程序而言,实现功能开关也是一项重要的任务。而 Unleash 是一个功能切换服务,它提供了一种简单且可扩展的方式来管理和控制应用程序的功能切换。因此本文小编将为大家介绍如何在 NestJS 应用程序中使用 Unleash 实现功能切换。下面是具体的操作步骤:
安装 NestJS
NestJS 的安装非常简单,在安装之前需要确保你的机器中已经安装了 Node,然后执行以下命令即可在全局安装 NestJS。
npm i -g @nestjs/cli
nest new project-name (creates a new project with all scaffoldings and bolerplate code)
创建后的项目结构:

安装 Unleash 服务器
选择 unleash 服务器的 docker 基础安装,使用下面的 docker compose 文件来启动 Unleash 服务器。
docker-compose up -d --build (run this command where you have dockercompose file)
This docker compose setup configures:
- the Unleash server instance + the necessary backing Postgres database
- the Unleash proxy
#
To learn more about all the parts of Unleash, visit
https://docs.getunleash.io
#
NOTE: please do not use this configuration for production setups.
Unleash does not take responsibility for any data leaks or other
problems that may arise as a result.
#
This is intended to be used for demo, development, and learning
purposes only.
version: "3.9"
services:
The Unleash server contains the Unleash configuration and
communicates with server-side SDKs and the Unleash Proxy
web:
image: unleashorg/unleash-server:latest
ports:
- "4242:4242"
environment:
This points Unleash to its backing database (defined in the
DATABASE_URL: "postgres://postgres:unleash@db/postgres"
Disable SSL for database connections. @chriswk: why do we do this?
DATABASE_SSL: "false"
Changing log levels:
LOG_LEVEL: "warn"
Proxy clients must use one of these keys to connect to the
Proxy. To add more keys, separate them with a comma (
INIT_FRONTEND_API_TOKENS: "default:development.unleash-insecure-frontend-api-token"
Initialize Unleash with a default set of client API tokens. To
initialize Unleash with multiple tokens, separate them with a
comma (
INIT_CLIENT_API_TOKENS: "default:development.unleash-insecure-api-token"
depends_on:
db:
condition: service_healthy
command: [ "node", "index.js" ]
healthcheck:
test: wget --no-verbose --tries=1 --spider http://localhost:4242/health || exit 1
interval: 1s
timeout: 1m
retries: 5
start_period: 15s
db:
expose:
- "5432"
image: postgres:15
environment:
create a database called
POSTGRES_DB: "db"
trust incoming connections blindly (DON'T DO THIS IN PRODUCTION!)
POSTGRES_HOST_AUTH_METHOD: "trust"
healthcheck:
test:
[
"CMD",
"pg_isready",
"--username=postgres",
"--host=127.0.0.1",
"--port=5432"
]
interval: 2s
timeout: 1m
retries: 5
start_period: 10s
使用unleash实现功能切换
现在已经有了代码库并启动并运行了 unleash 服务器,在开始其他任何事情之前,需要先安装一些依赖项。
yarn add unleash-client @nestjs/config
然后在项目的根目录中添加一个 .env 文件。
APP_NAME=nestjs-experimental-feature-toggle
API_KEY=<YOUR SERVER KEY>
UNLEASH_API_ENDPOINT=http://localhost:4242/api
METRICS_INTERVAL=1
REFRESH_INTERVAL=1
SERVER_PORT=3000
从 app.module.ts 文件开始。这是初始化并注入到引导文件 main.ts 的文件。
在此文件中,注入所有控制器、服务器和其他模块,如下所示。
ConfigModule.forRoot() 将扫描根目录中的 .env 文件并将其加载到应用程序中。
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { AppController } from './controllers/app.controller';
import { AppService } from './services/app.service';
@Module({
imports: [ConfigModule.forRoot()],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
main.ts 是引导文件
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import * as process from 'process';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(process.env.SERVER_PORT);
}
bootstrap();
现在构建名为 app.service.ts 的服务器层,如下所示。
import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
private response = {};
constructor() {
this.response['XS'] = '5';
this.response['S'] = '15';
this.response['M'] = '25';
this.response['L'] = '38';
this.response['XL'] = '28';
this.response['XXL'] = '15';
}
dataAnalytics = (): any => {
return this.response;
};
}
创建控制器 app.controller.ts ,它由以下多个部分组成:
1. constructor 是注入类所需的依赖项。
2. init 是使用所需的配置初始化 Unleash 客户端库。
3. dataAnalytics 是检查切换开关状态,并根据该状态决定要做什么的方法。
import { Controller, Get, Logger } from '@nestjs/common';
import { AppService } from '../services/app.service';
import { startUnleash, Unleash } from 'unleash-client';
import { ConfigService } from '@nestjs/config';
@Controller('/api/v1')
export class AppController {
private unleash: Unleash;
private readonly logger: Logger = new Logger(AppController.name);
constructor(
private readonly appService: AppService,
private readonly configService: ConfigService,
) {
this.init();
}
private init = async (): Promise<void> => {
this.unleash = await startUnleash({
url: this.configService.get<string('UNLEASH_API_ENDPOINT'),
appName: 'beta-api',
metricsInterval: parseInt(this.configService.get('METRICS_INTERVAL'), 10),
refreshInterval: parseInt(this.configService.get('REFRESH_INTERVAL'), 10),
customHeaders: {
Authorization: this.configService.get<string('API_KEY'),
},
});
};
@Get('/analytics')
dataAnalytics(): any {
// Unleash SDK has now fresh state from the unleash-api
const isEnabled: boolean = this.unleash.isEnabled('beta-api');
this.logger.log(`feature switch "beta-api" is ${isEnabled}`);
if (isEnabled) {
return this.appService.dataAnalytics();
} else {
return {
response: 'can not access this api as its in experimental mode',
};
}
}
}
紧接着需要在 unleash 中创建一个功能切换,使用 url 访问 unleash 的 Web 控制台:http://localhost:4242
单击默认项目并创建一个新的切换并向切换添加策略,在例子中,小编选择了 Gradual rollout 策略。创建功能切换后,前往项目设置并创建项目访问令牌(创建服务器端访问令牌)。
Web 控制台显示如下:



运行以下命令,您会看到如下内容:
| PowerShell yarn start:dev |
|---|

选择任何你最喜欢的 API 测试工具,比如 postman on insomnia 或其他任何东西,小编喜欢用insomnia 来测试 API。现在可通过切换开关来测试 API,并查看 Application 的表现。


结论
本文介绍了如何安装NestJS和Unleash服务器以及如何使用Unleash实现功能切换。通过本文的指导,读者能够快速搭建并配置这两个工具,以便在应用中灵活控制功能。
Redis从入门到实践
一节课带你搞懂数据库事务!
Chrome开发者工具使用教程
扩展链接:
在NestJS应用程序中使用 Unleash 实现功能切换的指南的更多相关文章
- Shepherd – 在应用程序中轻松实现引导功能
Shepherd 是一个指导用户使用应用程序的 JavaScript 库.它使用 Tether——另一个开源库,实现所有的步骤.Tether 确保你的步骤不会溢出屏幕或被剪裁.你可以很容易地指导用户使 ...
- WinForm应用程序中实现自动更新功能
WinForm应用程序中实现自动更新功能 编写人:左丘文 2015-4-20 近来在给一客户实施ECM系统,但他们使用功能并不是我们ECM制造版提供的标准功能,他们要求对系统作一些定制功能,为了避免因 ...
- 在java程序中实现发送邮件的功能
最近比较忙,在做一个人事管理系统的项目,在这项目需求中,需要一个发送邮件的功能.这个时候我们可以使用javamail的jar包来实现完美需要的功能,在这里简单的分享一个最基础的发邮件功能. 首先我们需 ...
- 远程控制篇:在DELPHI程序中拨号上网
用MODEM拨号上网,仍是大多数个人网民选择上网的方式.如果能在我们的应用程序中启动拨号连接(如IE浏览器程序中的自动拨号功能),无疑将会方便我们的软件用户(不用再切换应用程序,运行拨号网络),提高我 ...
- WINCE平台下C#应用程序中使用看门狗
看门狗定时器(WDT,Watch Dog Timer)是单片机的一个组成部分,它实际上是一个计数器,一般给看门狗一个大数,程序开始运行后看门狗开始倒计数.如果程序运行正常,过一段时间CPU应发出指令让 ...
- 对于是否在一个python程序中编写函数的启发
那我们到底是应该直接使用这些模块级别的函数呢,还是先编译一个模式对象,再调用模式对象的方法呢?这其实取决于正则表达式的使用频率,如果说我们这个程序只是偶尔使用到正则表达式,那么全局函数是比较方便的:如 ...
- APP开发者如何从应用程序中赚钱?
付费应用程序,这是应用程序最基本的赚钱方式之一,也是拥有巨大潜力的赚钱方式之一.但有一个问题开发者必须扪心自问,您的程序用户是否有一批粉丝级用户的认可,或对您应用程序品牌的认可 蝉大师APP推广工 ...
- 如何在微信小程序中实现音视频通话
微信小程序的音视频通话可以通过微信提供的实时音视频能力实现.这个能力包括了音视频采集.编码.传输和解码等多个环节,开发者只需要使用微信提供的 API 接口就可以轻松地实现音视频通话功能. 在具体实现上 ...
- 微信小程序实现即时通信聊天功能的实例代码
项目背景:小程序中实现实时聊天功能 一.服务器域名配置 配置流程 配置参考URL:https://developers.weixin.qq.com/miniprogram/dev/api/api-ne ...
- h5内嵌微信小程序,调用微信支付功能
在小程序中不能使用之前在浏览器中配置的支付功能,只能调用小程序专属的api进行支付. 因为需要在现在实现的基础上,再添加在小程序中调用微信支付功能,所以我的思路是这样的 1.在点击支付按钮时,判断是不 ...
随机推荐
- Linux 软件包:添加repo、升级内核、编译内核、交叉编译
添加 repo 增加 xxx.repo 文件 在/etc/yum.repos.d/目录下创建 add_openeuler_repo.repo 文件 [add_repo] name=add_repo b ...
- vulnhub Necromancer wp
flag1 nmap -sU -T4 192.168.220.130 有666端口 nc -nvu 192.168.220.130 666 监听回显消息 tcpdump host 192.168.22 ...
- redis 中的 list
lpush K1 V1 V2 V3 左边加入list rpush k1 v1 v2 v3 右边加入list lpop k1 左边吐出一个值 rpop k1 右边吐出一个值 lrange k1 0 ...
- Go语言中指针详解
指针在 Go 语言中是一个重要的特性,它允许你引用和操作变量的内存地址.下面是指针的主要作用和相关示例代码: 1. 引用传递 在 Go 中,所有的变量传递都是值传递,即复制变量的值.如果你想在一个函数 ...
- pylink
1.https://github.com/square/pylink/pull/72
- NOIP 2022 VP游记
总结:挂大分. HA NOIP没初中生的份,VP. CSP-S 图论专场 NOIP 数数专场. CCF 我服你. T1 看完之后,感觉不难,瞎搞了 40min+,过了大样例. 对拍不会写. T2 猜不 ...
- PIP升级+安装Django命令[WARNING: Retrying (Retry(total=4, connect=None...]
升级: >pip install -U Django 安装: >pip install Django 如果发现超时错误内容:(WARNING: Retrying (Retry(total= ...
- VMware Work Station使用ubuntu20.04挂载共享文件夹写入文件时出现输入/输出错误
原因是默认的max_write为0x00020000即128k,超过此大小会报错,另外big_writes,umask等选项也要加上, sudo /usr/bin/vmhgfs-fuse .host: ...
- 详解RecyclerView的预布局
概述 RecyclerView 的预布局用于 Item 动画中,也叫做预测动画.其用于当 Item 项进行变化时执行的一次布局过程(如添加或删除 Item 项),使 ItemAnimator 体验更加 ...
- 如何vue3中使用全局变量,与Vue2的区别
对比: 在vue2.x中我们挂载全局变量或方法是通过是使用Vue.prototype.$xxxx=xxx的形式来挂载,然后通过this.$xxx来获取挂载到全局的变量或者方法 但是 在vue3.x中显 ...