All files / src/lib/db feature-toggle-store.ts

79.69% Statements 51/64
76.92% Branches 10/13
74.07% Functions 20/27
79.03% Lines 49/62

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    69x 69x 69x         69x                                               69x   69x               87x 87x 87x                                           9x           271x                           48x       48x                                 131x       130x   1x 1x                                             4x 4x 4x                               822x 166x   656x 656x 656x                           81x 3x   78x 78x   78x       263x                   263x 248x   263x             245x 245x       245x                     18x       18x       12x       12x       3x           3x       3x       81x     81x               108x       108x       69x  
import { Knex } from 'knex';
import EventEmitter from 'events';
import metricsHelper from '../util/metrics-helper';
import { DB_TIME } from '../metric-events';
import NotFoundError from '../error/notfound-error';
import { Logger, LogProvider } from '../logger';
import { FeatureToggle, FeatureToggleDTO, IVariant } from '../types/model';
import { IFeatureToggleStore } from '../types/stores/feature-toggle-store';
 
const FEATURE_COLUMNS = [
    'name',
    'description',
    'type',
    'project',
    'stale',
    'variants',
    'created_at',
    'impression_data',
    'last_seen_at',
];
 
export interface FeaturesTable {
    name: string;
    description: string;
    type: string;
    stale: boolean;
    variants?: string;
    project: string;
    last_seen_at?: Date;
    created_at?: Date;
    impression_data: boolean;
}
 
const TABLE = 'features';
 
export default class FeatureToggleStore implements IFeatureToggleStore {
    private db: Knex;
 
    private logger: Logger;
 
    private timer: Function;
 
    constructor(db: Knex, eventBus: EventEmitter, getLogger: LogProvider) {
        this.db = db;
        this.logger = getLogger('feature-toggle-store.ts');
        this.timer = (action) =>
            metricsHelper.wrapTimer(eventBus, DB_TIME, {
                store: 'feature-toggle',
                action,
            });
    }
 
    async count(
        query: {
            archived?: boolean;
            project?: string;
            stale?: boolean;
        } = { archived: false },
    ): Promise<number> {
        return this.db
            .from(TABLE)
            .count('*')
            .where(query)
            .then((res) => Number(res[0].count));
    }
 
    async deleteAll(): Promise<void> {
        await this.db(TABLE).del();
    }
 
    destroy(): void {}
 
    async get(name: string): Promise<FeatureToggle> {
        return this.db
            .first(FEATURE_COLUMNS)
            .from(TABLE)
            .where({ name })
            .then(this.rowToFeature);
    }
 
    async getAll(
        query: {
            archived?: boolean;
            project?: string;
            stale?: boolean;
        } = { archived: false },
    ): Promise<FeatureToggle[]> {
        const rows = await this.db
            .select(FEATURE_COLUMNS)
            .from(TABLE)
            .where(query);
        return rows.map(this.rowToFeature);
    }
 
    async getFeatures(archived: boolean): Promise<FeatureToggle[]> {
        const rows = await this.db
            .select(FEATURE_COLUMNS)
            .from(TABLE)
            .where({ archived });
        return rows.map(this.rowToFeature);
    }
 
    /**
     * Get projectId from feature filtered by name. Used by Rbac middleware
     * @deprecated
     * @param name
     */
    async getProjectId(name: string): Promise<string> {
        return this.db
            .first(['project'])
            .from(TABLE)
            .where({ name })
            .then((r) => (r ? r.project : undefined))
            .catch((e) => {
                this.logger.error(e);
                return undefined;
            });
    }
 
    async exists(name: string): Promise<boolean> {
        const result = await this.db.raw(
            'SELECT EXISTS (SELECT 1 FROM features WHERE name = ?) AS present',
            [name],
        );
        const { present } = result.rows[0];
        return present;
    }
 
    async getArchivedFeatures(): Promise<FeatureToggle[]> {
        const rows = await this.db
            .select(FEATURE_COLUMNS)
            .from(TABLE)
            .where({ archived: true })
            .orderBy('name', 'asc');
        return rows.map(this.rowToFeature);
    }
 
    async setLastSeen(toggleNames: string[]): Promise<void> {
        const now = new Date();
        try {
            await this.db(TABLE)
                .update({ last_seen_at: now })
                .whereIn(
                    'name',
                    this.db(TABLE)
                        .select('name')
                        .whereIn('name', toggleNames)
                        .forUpdate()
                        .skipLocked(),
                );
        } catch (err) {
            this.logger.error('Could not update lastSeen, error: ', err);
        }
    }
 
    rowToFeature(row: FeaturesTable): FeatureToggle {
        if (!row) {
            throw new NotFoundError('No feature toggle found');
        }
        const sortedVariants = (row.variants as unknown as IVariant[]) || [];
        sortedVariants.sort((a, b) => a.name.localeCompare(b.name));
        return {
            name: row.name,
            description: row.description,
            type: row.type,
            project: row.project,
            stale: row.stale,
            variants: sortedVariants,
            createdAt: row.created_at,
            lastSeenAt: row.last_seen_at,
            impressionData: row.impression_data,
        };
    }
 
    rowToVariants(row: FeaturesTable): IVariant[] {
        if (!row) {
            throw new NotFoundError('No feature toggle found');
        }
        const sortedVariants = (row.variants as unknown as IVariant[]) || [];
        sortedVariants.sort((a, b) => a.name.localeCompare(b.name));
 
        return sortedVariants;
    }
 
    dtoToRow(project: string, data: FeatureToggleDTO): FeaturesTable {
        const row = {
            name: data.name,
            description: data.description,
            type: data.type,
            project,
            archived: data.archived || false,
            stale: data.stale,
            created_at: data.createdAt,
            impression_data: data.impressionData,
        };
        if (!row.created_at) {
            delete row.created_at;
        }
        return row;
    }
 
    async create(
        project: string,
        data: FeatureToggleDTO,
    ): Promise<FeatureToggle> {
        try {
            const row = await this.db(TABLE)
                .insert(this.dtoToRow(project, data))
                .returning(FEATURE_COLUMNS);
 
            return this.rowToFeature(row[0]);
        } catch (err) {
            this.logger.error('Could not insert feature, error: ', err);
        }
        return undefined;
    }
 
    async update(
        project: string,
        data: FeatureToggleDTO,
    ): Promise<FeatureToggle> {
        const row = await this.db(TABLE)
            .where({ name: data.name })
            .update(this.dtoToRow(project, data))
            .returning(FEATURE_COLUMNS);
        return this.rowToFeature(row[0]);
    }
 
    async archive(name: string): Promise<FeatureToggle> {
        const row = await this.db(TABLE)
            .where({ name })
            .update({ archived: true })
            .returning(FEATURE_COLUMNS);
        return this.rowToFeature(row[0]);
    }
 
    async delete(name: string): Promise<void> {
        await this.db(TABLE)
            .where({ name, archived: true }) // Feature toggle must be archived to allow deletion
            .del();
    }
 
    async revive(name: string): Promise<FeatureToggle> {
        const row = await this.db(TABLE)
            .where({ name })
            .update({ archived: false })
            .returning(FEATURE_COLUMNS);
        return this.rowToFeature(row[0]);
    }
 
    async getVariants(featureName: string): Promise<IVariant[]> {
        const row = await this.db(TABLE)
            .select('variants')
            .where({ name: featureName });
        return this.rowToVariants(row[0]);
    }
 
    async saveVariants(
        project: string,
        featureName: string,
        newVariants: IVariant[],
    ): Promise<FeatureToggle> {
        const row = await this.db(TABLE)
            .update({ variants: JSON.stringify(newVariants) })
            .where({ project: project, name: featureName })
            .returning(FEATURE_COLUMNS);
        return this.rowToFeature(row[0]);
    }
}
 
module.exports = FeatureToggleStore;