前言
近年來,軟件開發行業迅速發展,功能開關(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開發者工具使用教程
擴展鏈接: