前语
近年来,软件开发职业迅速发展,功用开关(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从入门到实践