All files / src/lib/routes/admin-api/project features.ts

92.5% Statements 111/120
100% Branches 0/0
89.47% Functions 17/19
92.5% Lines 111/120

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617  59x 59x         59x                   59x   59x 59x     59x   59x 59x 59x 59x 59x 59x 59x 59x 59x             59x                                               59x 59x 59x 59x 59x 59x             59x     141x   141x                 141x 141x 141x   141x                             141x                           141x                           141x                             141x                             141x                             141x                           141x                           141x                             141x                             141x                             141x                               141x                             141x                               141x                               141x                                       2x 2x     2x                       3x 3x 3x 3x             3x             80x   80x 80x           77x             21x 21x 19x                       8x 8x 8x 8x           6x                       7x 7x           5x                         1x 1x 1x 1x             6x 6x         5x             11x 11x             9x             3x 3x             2x             43x 43x 43x         39x             4x   4x         3x                 9x 9x 9x           5x             1x 1x 1x 1x 1x 1x           1x             3x 3x 3x 3x 2x             5x 5x 5x 5x 5x 5x         4x                                                                          
import { Request, Response } from 'express';
import { applyPatch, Operation } from 'fast-json-patch';
import Controller from '../../controller';
import { IUnleashConfig } from '../../../types/option';
import { IUnleashServices } from '../../../types';
import FeatureToggleService from '../../../services/feature-toggle-service';
import { Logger } from '../../../logger';
import {
    CREATE_FEATURE,
    CREATE_FEATURE_STRATEGY,
    DELETE_FEATURE,
    DELETE_FEATURE_STRATEGY,
    NONE,
    UPDATE_FEATURE,
    UPDATE_FEATURE_ENVIRONMENT,
    UPDATE_FEATURE_STRATEGY,
} from '../../../types/permissions';
import { extractUsername } from '../../../util/extract-user';
import { IAuthRequest } from '../../unleash-types';
import { createFeatureRequest } from '../../../openapi/spec/create-feature-request';
import { featureResponse } from '../../../openapi/spec/feature-response';
import { CreateFeatureSchema } from '../../../openapi/spec/create-feature-schema';
import { FeatureSchema } from '../../../openapi/spec/feature-schema';
import { createStrategyRequest } from '../../../openapi/spec/create-strategy-request';
import { StrategySchema } from '../../../openapi/spec/strategy-schema';
import { featuresResponse } from '../../../openapi/spec/features-response';
import { featureEnvironmentInfoResponse } from '../../../openapi/spec/feature-environment-info-response';
import { strategiesResponse } from '../../../openapi/spec/strategies-response';
import { strategyResponse } from '../../../openapi/spec/strategy-response';
import { emptyResponse } from '../../../openapi/spec/empty-response';
import { updateFeatureRequest } from '../../../openapi/spec/update-feature-request';
import { patchRequest } from '../../../openapi/spec/patch-request';
import { updateStrategyRequest } from '../../../openapi/spec/update-strategy-request';
import { cloneFeatureRequest } from '../../../openapi/spec/clone-feature-request';
import { FeatureEnvironmentInfoSchema } from '../../../openapi/spec/feature-environment-info-schema';
import { ParametersSchema } from '../../../openapi/spec/parameters-schema';
import { FeaturesSchema } from '../../../openapi/spec/features-schema';
import { UpdateFeatureSchema } from '../../../openapi/spec/updateFeatureSchema';
import { UpdateStrategySchema } from '../../../openapi/spec/update-strategy-schema';
import { CreateStrategySchema } from '../../../openapi/spec/create-strategy-schema';
import {
    EnvironmentInfoMapper,
    StrategyMapper,
} from '../../../openapi/mappers';
 
interface FeatureStrategyParams {
    projectId: string;
    featureName: string;
    environment: string;
    sortOrder?: number;
}
 
interface FeatureParams extends ProjectParam {
    featureName: string;
}
 
interface ProjectParam {
    projectId: string;
}
 
interface StrategyIdParams extends FeatureStrategyParams {
    strategyId: string;
}
 
const PATH = '/:projectId/features';
const PATH_FEATURE = `${PATH}/:featureName`;
const PATH_FEATURE_CLONE = `${PATH_FEATURE}/clone`;
const PATH_ENV = `${PATH_FEATURE}/environments/:environment`;
const PATH_STRATEGIES = `${PATH_ENV}/strategies`;
const PATH_STRATEGY = `${PATH_STRATEGIES}/:strategyId`;
 
type ProjectFeaturesServices = Pick<
    IUnleashServices,
    'featureToggleServiceV2' | 'projectHealthService' | 'openApiService'
>;
 
export default class ProjectFeaturesController extends Controller {
    private featureService: FeatureToggleService;
 
    private strategyMapper: StrategyMapper = new StrategyMapper();
 
    private environmentMapper: EnvironmentInfoMapper =
        new EnvironmentInfoMapper();
 
    private readonly logger: Logger;
 
    constructor(
        config: IUnleashConfig,
        { featureToggleServiceV2, openApiService }: ProjectFeaturesServices,
    ) {
        super(config);
        this.featureService = featureToggleServiceV2;
        this.logger = config.getLogger('/admin-api/project/features.ts');
 
        this.route({
            method: 'get',
            path: PATH_ENV,
            acceptAnyContentType: true,
            permission: NONE,
            handler: this.getEnvironment,
            middleware: [
                openApiService.validPath({
                    tags: ['admin'],
                    operationId: 'getEnvironment',
                    responses: { 200: featureEnvironmentInfoResponse },
                }),
            ],
        });
 
        this.route({
            method: 'post',
            path: `${PATH_ENV}/off`,
            handler: this.toggleEnvironmentOff,
            permission: UPDATE_FEATURE_ENVIRONMENT,
            middleware: [
                openApiService.validPath({
                    tags: ['admin'],
                    operationId: 'toggleEnvironmentOff',
                    responses: { 200: featureResponse },
                }),
            ],
        });
 
        this.route({
            method: 'post',
            path: `${PATH_ENV}/on`,
            handler: this.toggleEnvironmentOn,
            permission: UPDATE_FEATURE_ENVIRONMENT,
            middleware: [
                openApiService.validPath({
                    tags: ['admin'],
                    operationId: 'toggleEnvironmentOn',
                    responses: { 200: featureResponse },
                }),
            ],
        });
 
        this.route({
            method: 'get',
            path: PATH_STRATEGIES,
            handler: this.getStrategies,
            acceptAnyContentType: true,
            permission: NONE,
            middleware: [
                openApiService.validPath({
                    tags: ['admin'],
                    operationId: 'getStrategies',
                    responses: { 200: strategiesResponse },
                }),
            ],
        });
 
        this.route({
            method: 'post',
            path: PATH_STRATEGIES,
            handler: this.addStrategy,
            permission: CREATE_FEATURE_STRATEGY,
            middleware: [
                openApiService.validPath({
                    tags: ['admin'],
                    operationId: 'addStrategy',
                    requestBody: createStrategyRequest,
                    responses: { 200: strategyResponse },
                }),
            ],
        });
 
        this.route({
            method: 'get',
            path: PATH_STRATEGY,
            handler: this.getStrategy,
            acceptAnyContentType: true,
            permission: NONE,
            middleware: [
                openApiService.validPath({
                    tags: ['admin'],
                    operationId: 'getStrategy',
                    responses: { 200: strategyResponse },
                }),
            ],
        });
 
        this.route({
            method: 'put',
            path: PATH_STRATEGY,
            handler: this.updateStrategy,
            permission: UPDATE_FEATURE_STRATEGY,
            middleware: [
                openApiService.validPath({
                    tags: ['admin'],
                    operationId: 'updateStrategy',
                    requestBody: updateStrategyRequest,
                    responses: { 200: strategyResponse },
                }),
            ],
        });
        this.route({
            method: 'patch',
            path: PATH_STRATEGY,
            handler: this.patchStrategy,
            permission: UPDATE_FEATURE_STRATEGY,
            middleware: [
                openApiService.validPath({
                    tags: ['admin'],
                    operationId: 'patchStrategy',
                    requestBody: patchRequest,
                    responses: { 200: strategyResponse },
                }),
            ],
        });
        this.route({
            method: 'delete',
            path: PATH_STRATEGY,
            acceptAnyContentType: true,
            handler: this.deleteStrategy,
            permission: DELETE_FEATURE_STRATEGY,
            middleware: [
                openApiService.validPath({
                    operationId: 'deleteStrategy',
                    tags: ['admin'],
                    responses: { 200: emptyResponse },
                }),
            ],
        });
 
        this.route({
            method: 'get',
            path: PATH,
            acceptAnyContentType: true,
            handler: this.getFeatures,
            permission: NONE,
            middleware: [
                openApiService.validPath({
                    tags: ['admin'],
                    operationId: 'getFeatures',
                    responses: { 200: featuresResponse },
                }),
            ],
        });
 
        this.route({
            method: 'post',
            path: PATH,
            handler: this.createFeature,
            permission: CREATE_FEATURE,
            middleware: [
                openApiService.validPath({
                    tags: ['admin'],
                    operationId: 'createFeature',
                    requestBody: createFeatureRequest,
                    responses: { 200: featureResponse },
                }),
            ],
        });
 
        this.route({
            method: 'post',
            path: PATH_FEATURE_CLONE,
            acceptAnyContentType: true,
            handler: this.cloneFeature,
            permission: CREATE_FEATURE,
            middleware: [
                openApiService.validPath({
                    tags: ['admin'],
                    operationId: 'cloneFeature',
                    requestBody: cloneFeatureRequest,
                    responses: { 200: featureResponse },
                }),
            ],
        });
 
        this.route({
            method: 'get',
            path: PATH_FEATURE,
            acceptAnyContentType: true,
            handler: this.getFeature,
            permission: NONE,
            middleware: [
                openApiService.validPath({
                    operationId: 'getFeature',
                    tags: ['admin'],
                    responses: { 200: featureResponse },
                }),
            ],
        });
 
        this.route({
            method: 'put',
            path: PATH_FEATURE,
            acceptAnyContentType: true,
            handler: this.updateFeature,
            permission: UPDATE_FEATURE,
            middleware: [
                openApiService.validPath({
                    tags: ['admin'],
                    operationId: 'updateFeature',
                    requestBody: updateFeatureRequest,
                    responses: { 200: featureResponse },
                }),
            ],
        });
 
        this.route({
            method: 'patch',
            path: PATH_FEATURE,
            acceptAnyContentType: true,
            handler: this.patchFeature,
            permission: UPDATE_FEATURE,
            middleware: [
                openApiService.validPath({
                    tags: ['admin'],
                    operationId: 'patchFeature',
                    requestBody: patchRequest,
                    responses: { 200: featureResponse },
                }),
            ],
        });
 
        this.route({
            method: 'delete',
            path: PATH_FEATURE,
            acceptAnyContentType: true,
            handler: this.archiveFeature,
            permission: DELETE_FEATURE,
            middleware: [
                openApiService.validPath({
                    tags: ['admin'],
                    operationId: 'archiveFeature',
                    responses: { 200: emptyResponse },
                }),
            ],
        });
    }
 
    async getFeatures(
        req: Request<ProjectParam, any, any, any>,
        res: Response<FeaturesSchema>,
    ): Promise<void> {
        const { projectId } = req.params;
        const features = await this.featureService.getFeatureOverview(
            projectId,
        );
        res.json({ version: 1, features });
    }
 
    async cloneFeature(
        req: IAuthRequest<
            FeatureParams,
            any,
            { name: string; replaceGroupId?: boolean },
            any
        >,
        res: Response<FeatureSchema>,
    ): Promise<void> {
        const { projectId, featureName } = req.params;
        const { name, replaceGroupId } = req.body;
        const userName = extractUsername(req);
        const created = await this.featureService.cloneFeatureToggle(
            featureName,
            projectId,
            name,
            replaceGroupId,
            userName,
        );
        res.status(201).json(created);
    }
 
    async createFeature(
        req: IAuthRequest<FeatureParams, FeatureSchema, CreateFeatureSchema>,
        res: Response<FeatureSchema>,
    ): Promise<void> {
        const { projectId } = req.params;
 
        const userName = extractUsername(req);
        const created = await this.featureService.createFeatureToggle(
            projectId,
            req.body,
            userName,
        );
 
        res.status(201).json(created);
    }
 
    async getFeature(
        req: Request<FeatureParams, any, any, any>,
        res: Response,
    ): Promise<void> {
        const { featureName } = req.params;
        const feature = await this.featureService.getFeature(featureName);
        res.status(200).json(feature);
    }
 
    async updateFeature(
        req: IAuthRequest<
            { projectId: string; featureName: string },
            any,
            UpdateFeatureSchema,
            any
        >,
        res: Response<FeatureSchema>,
    ): Promise<void> {
        const { projectId, featureName } = req.params;
        const data = req.body;
        const userName = extractUsername(req);
        const created = await this.featureService.updateFeatureToggle(
            projectId,
            data,
            userName,
            featureName,
        );
        res.status(200).json(created);
    }
 
    async patchFeature(
        req: IAuthRequest<
            { projectId: string; featureName: string },
            any,
            Operation[],
            any
        >,
        res: Response<FeatureSchema>,
    ): Promise<void> {
        const { projectId, featureName } = req.params;
        const updated = await this.featureService.patchFeature(
            projectId,
            featureName,
            extractUsername(req),
            req.body,
        );
        res.status(200).json(updated);
    }
 
    // TODO: validate projectId
    async archiveFeature(
        req: IAuthRequest<
            { projectId: string; featureName: string },
            any,
            any,
            any
        >,
        res: Response<void>,
    ): Promise<void> {
        const { featureName } = req.params;
        const userName = extractUsername(req);
        await this.featureService.archiveToggle(featureName, userName);
        res.status(202).send();
    }
 
    async getEnvironment(
        req: Request<FeatureStrategyParams, any, any, any>,
        res: Response<FeatureEnvironmentInfoSchema>,
    ): Promise<void> {
        const { environment, featureName, projectId } = req.params;
        const environmentInfo = await this.featureService.getEnvironmentInfo(
            projectId,
            environment,
            featureName,
        );
        res.status(200).json(this.environmentMapper.toPublic(environmentInfo));
    }
 
    async toggleEnvironmentOn(
        req: IAuthRequest<FeatureStrategyParams, any, any, any>,
        res: Response<void>,
    ): Promise<void> {
        const { featureName, environment, projectId } = req.params;
        await this.featureService.updateEnabled(
            projectId,
            featureName,
            environment,
            true,
            extractUsername(req),
        );
        res.status(200).end();
    }
 
    async toggleEnvironmentOff(
        req: IAuthRequest<FeatureStrategyParams, any, any, any>,
        res: Response<void>,
    ): Promise<void> {
        const { featureName, environment, projectId } = req.params;
        await this.featureService.updateEnabled(
            projectId,
            featureName,
            environment,
            false,
            extractUsername(req),
        );
        res.status(200).end();
    }
 
    async addStrategy(
        req: IAuthRequest<FeatureStrategyParams, any, CreateStrategySchema>,
        res: Response<StrategySchema>,
    ): Promise<void> {
        const { projectId, featureName, environment } = req.params;
        const userName = extractUsername(req);
        const strategy = await this.featureService.createStrategy(
            this.strategyMapper.mapInput(req.body),
            { environment, projectId, featureName },
            userName,
        );
        res.status(200).json(this.strategyMapper.toPublic(strategy));
    }
 
    async getStrategies(
        req: Request<FeatureStrategyParams, any, any, any>,
        res: Response<StrategySchema[]>,
    ): Promise<void> {
        const { projectId, featureName, environment } = req.params;
        const featureStrategies =
            await this.featureService.getStrategiesForEnvironment(
                projectId,
                featureName,
                environment,
            );
        res.status(200).json(
            featureStrategies.map(this.strategyMapper.toPublic),
        );
    }
 
    async updateStrategy(
        req: IAuthRequest<StrategyIdParams, any, UpdateStrategySchema>,
        res: Response<StrategySchema>,
    ): Promise<void> {
        const { strategyId, environment, projectId, featureName } = req.params;
        const userName = extractUsername(req);
        const updatedStrategy = await this.featureService.updateStrategy(
            strategyId,
            req.body,
            { environment, projectId, featureName },
            userName,
        );
        res.status(200).json(this.strategyMapper.fromPublic(updatedStrategy));
    }
 
    async patchStrategy(
        req: IAuthRequest<StrategyIdParams, any, Operation[], any>,
        res: Response<StrategySchema>,
    ): Promise<void> {
        const { strategyId, projectId, environment, featureName } = req.params;
        const userName = extractUsername(req);
        const patch = req.body;
        const strategy = await this.featureService.getStrategy(strategyId);
        const { newDocument } = applyPatch(strategy, patch);
        const updatedStrategy = await this.featureService.updateStrategy(
            strategyId,
            newDocument,
            { environment, projectId, featureName },
            userName,
        );
        res.status(200).json(this.strategyMapper.toPublic(updatedStrategy));
    }
 
    async getStrategy(
        req: IAuthRequest<StrategyIdParams, any, any, any>,
        res: Response<StrategySchema>,
    ): Promise<void> {
        this.logger.info('Getting strategy');
        const { strategyId } = req.params;
        this.logger.info(strategyId);
        const strategy = await this.featureService.getStrategy(strategyId);
        res.status(200).json(this.strategyMapper.toPublic(strategy));
    }
 
    async deleteStrategy(
        req: IAuthRequest<StrategyIdParams, any, any, any>,
        res: Response<void>,
    ): Promise<void> {
        this.logger.info('Deleting strategy');
        const { environment, projectId, featureName } = req.params;
        const userName = extractUsername(req);
        const { strategyId } = req.params;
        this.logger.info(strategyId);
        const strategy = await this.featureService.deleteStrategy(
            strategyId,
            { environment, projectId, featureName },
            userName,
        );
        res.status(200).json(strategy);
    }
 
    async updateStrategyParameter(
        req: IAuthRequest<
            StrategyIdParams,
            any,
            { name: string; value: string | number },
            any
        >,
        res: Response<StrategySchema>,
    ): Promise<void> {
        const { strategyId, environment, projectId, featureName } = req.params;
        const userName = extractUsername(req);
        const { name, value } = req.body;
 
        const updatedStrategy =
            await this.featureService.updateStrategyParameter(
                strategyId,
                name,
                value,
                { environment, projectId, featureName },
                userName,
            );
        res.status(200).json(this.strategyMapper.toPublic(updatedStrategy));
    }
 
    async getStrategyParameters(
        req: Request<StrategyIdParams, any, any, any>,
        res: Response<ParametersSchema>,
    ): Promise<void> {
        this.logger.info('Getting strategy parameters');
        const { strategyId } = req.params;
        const strategy = await this.featureService.getStrategy(strategyId);
        res.status(200).json(strategy.parameters);
    }
}