# All files / modules/feature-flags/services feature-flags.service.ts

91.39% Statements 85/93
60% Branches 30/50
84.21% Functions 16/19
91.2% Lines 83/91

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
    3092x

    2x
    2x
    2x
    2x
    2x

    2x

    2x

    31x

    31x

    31x

    2x

    2x
    1x

    1x
    1x

    2x
    2x
    1x

    1x
    1x

    2x
    2x
    1x

    1x

    1x

    3x
    3x
    1x

    2x
    2x

    3x
    3x
    1x

    2x

    2x
    1x
    1x
    1x

    1x

    2x

    2x

    2x
    1x

    1x

    2x
    2x

    2x

    2x
    1x
    1x
    1x

    1x

    2x

    1x

    14x

    14x
    3x

    11x
    7x

    4x
    4x

    4x

    4x
    4x

    4x

    4x
    3x

    3x

    1x

    1x
    1x

    1x
    2x

    1x

    2x
    2x

    2x
    2x

    3x

    3x
    3x

    3x

     import {
      Injectable,
      NotFoundException,
      ConflictException,
    } from '@nestjs/common';
    import { InjectRepository } from '@nestjs/typeorm';
    import { Repository } from 'typeorm';
    import { FeatureFlag, FlagScope } from '../entities/feature-flag.entity';
    import { TenantFlag } from '../entities/tenant-flag.entity';
    import { UserFlag } from '../entities/user-flag.entity';
    import { CreateFlagDto } from '../dto/create-flag.dto';
    import { UpdateFlagDto } from '../dto/update-flag.dto';
    import { SetTenantFlagDto, SetUserFlagDto } from '../dto/set-tenant-flag.dto';
    import * as crypto from 'crypto';

    export interface EvaluationContext {
      tenantId?: string;
      userId?: string;
      planId?: string;
      attributes?: Record<string, any>;
    }

    export interface FlagEvaluation {
      key: string;
      enabled: boolean;
      value: any;
      source: 'default' | 'global' | 'tenant' | 'user' | 'rollout';
    }

    @Injectable()
    export class FeatureFlagsService {
      constructor(
        @InjectRepository(FeatureFlag)
        private readonly flagRepository: Repository<FeatureFlag>,
        @InjectRepository(TenantFlag)
        private readonly tenantFlagRepository: Repository<TenantFlag>,
        @InjectRepository(UserFlag)
        private readonly userFlagRepository: Repository<UserFlag>,
      ) {}

      // ==================== FLAG MANAGEMENT ====================

      async createFlag(dto: CreateFlagDto): Promise<FeatureFlag> {
        const existing = await this.flagRepository.findOne({
          where: { key: dto.key },
        });

        if (existing) {
          throw new ConflictException(`Flag with key '${dto.key}' already exists`);
        }

        const flag = this.flagRepository.create(dto);
        return this.flagRepository.save(flag);
      }

      async updateFlag(id: string, dto: UpdateFlagDto): Promise<FeatureFlag> {
        const flag = await this.flagRepository.findOne({ where: { id } });
        if (!flag) {
          throw new NotFoundException(`Flag with ID '${id}' not found`);
        }

        Object.assign(flag, dto);
        return this.flagRepository.save(flag);
      }

      async deleteFlag(id: string): Promise<void> {
        const flag = await this.flagRepository.findOne({ where: { id } });
        if (!flag) {
          throw new NotFoundException(`Flag with ID '${id}' not found`);
        }

        await this.flagRepository.remove(flag);
      }

      async getAllFlags(): Promise<FeatureFlag[]> {
        return this.flagRepository.find({
          order: { category: 'ASC', key: 'ASC' },
        });
      }

      async getFlagByKey(key: string): Promise<FeatureFlag | null> {
        return this.flagRepository.findOne({ where: { key } });
      }

      async getFlagById(id: string): Promise<FeatureFlag | null> {
        return this.flagRepository.findOne({ where: { id } });
      }

      async toggleFlag(id: string, enabled: boolean): Promise<FeatureFlag> {
        const flag = await this.flagRepository.findOne({ where: { id } });
        if (!flag) {
          throw new NotFoundException(`Flag with ID '${id}' not found`);
        }

        flag.is_enabled = enabled;
        return this.flagRepository.save(flag);
      }

      // ==================== TENANT FLAGS ====================

      async setTenantFlag(tenantId: string, dto: SetTenantFlagDto): Promise<TenantFlag> {
        const flag = await this.flagRepository.findOne({ where: { id: dto.flag_id } });
        if (!flag) {
          throw new NotFoundException(`Flag with ID '${dto.flag_id}' not found`);
        }

        let tenantFlag = await this.tenantFlagRepository.findOne({
          where: { tenant_id: tenantId, flag_id: dto.flag_id },
        });

        if (tenantFlag) {
          tenantFlag.is_enabled = dto.is_enabled ?? tenantFlag.is_enabled;
          tenantFlag.value = dto.value ?? tenantFlag.value;
          tenantFlag.metadata = dto.metadata ?? tenantFlag.metadata;
        } else {
          tenantFlag = this.tenantFlagRepository.create({
            tenant_id: tenantId,
            flag_id: dto.flag_id,
            is_enabled: dto.is_enabled ?? true,
            value: dto.value,
            metadata: dto.metadata,
          });
        }

        return this.tenantFlagRepository.save(tenantFlag);
      }

      async removeTenantFlag(tenantId: string, flagId: string): Promise<void> {
        const tenantFlag = await this.tenantFlagRepository.findOne({
          where: { tenant_id: tenantId, flag_id: flagId },
        });

        if (tenantFlag) {
          await this.tenantFlagRepository.remove(tenantFlag);
        }
      }

      async getTenantFlags(tenantId: string): Promise<TenantFlag[]> {
        return this.tenantFlagRepository.find({
          where: { tenant_id: tenantId },
          relations: ['flag'],
        });
      }

      // ==================== USER FLAGS ====================

      async setUserFlag(tenantId: string, dto: SetUserFlagDto): Promise<UserFlag> {
        const flag = await this.flagRepository.findOne({ where: { id: dto.flag_id } });
        Iif (!flag) {
          throw new NotFoundException(`Flag with ID '${dto.flag_id}' not found`);
        }

        let userFlag = await this.userFlagRepository.findOne({
          where: { user_id: dto.user_id, flag_id: dto.flag_id },
        });

        if (userFlag) {
          userFlag.is_enabled = dto.is_enabled ?? userFlag.is_enabled;
          userFlag.value = dto.value ?? userFlag.value;
          userFlag.metadata = dto.metadata ?? userFlag.metadata;
        } else {
          userFlag = this.userFlagRepository.create({
            tenant_id: tenantId,
            user_id: dto.user_id,
            flag_id: dto.flag_id,
            is_enabled: dto.is_enabled ?? true,
            value: dto.value,
            metadata: dto.metadata,
          });
        }

        return this.userFlagRepository.save(userFlag);
      }

      async removeUserFlag(userId: string, flagId: string): Promise<void> {
        const userFlag = await this.userFlagRepository.findOne({
          where: { user_id: userId, flag_id: flagId },
        });

        Iif (userFlag) {
          await this.userFlagRepository.remove(userFlag);
        }
      }

      async getUserFlags(tenantId: string, userId: string): Promise<UserFlag[]> {
        return this.userFlagRepository.find({
          where: { tenant_id: tenantId, user_id: userId },
          relations: ['flag'],
        });
      }

      // ==================== FLAG EVALUATION ====================

      async evaluateFlag(key: string, context: EvaluationContext): Promise<FlagEvaluation> {
        const flag = await this.flagRepository.findOne({ where: { key } });

        if (!flag) {
          return {
            key,
            enabled: false,
            value: null,
            source: 'default',
          };
        }

        // Global flag disabled
        if (!flag.is_enabled) {
          return {
            key,
            enabled: false,
            value: flag.default_value,
            source: 'global',
          };
        }

        // Check user-level override
        if (context.userId) {
          const userFlag = await this.userFlagRepository.findOne({
            where: { user_id: context.userId, flag_id: flag.id },
          });

          Iif (userFlag) {
            return {
              key,
              enabled: userFlag.is_enabled,
              value: userFlag.value ?? flag.default_value,
              source: 'user',
            };
          }
        }

        // Check tenant-level override
        if (context.tenantId) {
          const tenantFlag = await this.tenantFlagRepository.findOne({
            where: { tenant_id: context.tenantId, flag_id: flag.id },
          });

          Iif (tenantFlag) {
            return {
              key,
              enabled: tenantFlag.is_enabled,
              value: tenantFlag.value ?? flag.default_value,
              source: 'tenant',
            };
          }
        }

        // Check rollout percentage
        if (flag.rollout_percentage !== null && flag.rollout_percentage < 100) {
          const isInRollout = this.isInRollout(
            flag.rollout_percentage,
            context.userId || context.tenantId || 'anonymous',
            flag.key,
          );

          return {
            key,
            enabled: isInRollout,
            value: isInRollout ? flag.default_value : null,
            source: 'rollout',
          };
        }

        // Return global value
        return {
          key,
          enabled: flag.is_enabled,
          value: flag.default_value,
          source: 'global',
        };
      }

      async evaluateAllFlags(context: EvaluationContext): Promise<Record<string, FlagEvaluation>> {
        const flags = await this.flagRepository.find();
        const evaluations: Record<string, FlagEvaluation> = {};

        for (const flag of flags) {
          evaluations[flag.key] = await this.evaluateFlag(flag.key, context);
        }

        return evaluations;
      }

      async isEnabled(key: string, context: EvaluationContext): Promise<boolean> {
        const evaluation = await this.evaluateFlag(key, context);
        return evaluation.enabled;
      }

      async getValue<T = any>(key: string, context: EvaluationContext, defaultValue: T): Promise<T> {
        const evaluation = await this.evaluateFlag(key, context);
        return evaluation.enabled ? (evaluation.value ?? defaultValue) : defaultValue;
      }

      // ==================== HELPERS ====================

      private isInRollout(percentage: number, identifier: string, flagKey: string): boolean {
        // Create deterministic hash for consistent rollout
        const hash = crypto
          .createHash('md5')
          .update(`${flagKey}:${identifier}`)
          .digest('hex');

        const hashInt = parseInt(hash.substring(0, 8), 16);
        const normalized = hashInt / 0xffffffff;

        return normalized * 100 < percentage;
      }
    }