@weaverslab/feature-flags
Version:
Feature flags for CodeWeavers
43 lines (42 loc) • 1.45 kB
JavaScript
import dotenv from 'dotenv';
import { sql } from 'drizzle-orm';
import { drizzle } from 'drizzle-orm/postgres-js';
import EventEmitter from 'events';
import { LRUCache } from 'lru-cache';
import { Pool } from 'pg';
dotenv.config();
class FeatureFlagService {
constructor() {
this.db = drizzle(new Pool({ connectionString: process.env.DATABASE_URL }));
this.cache = new LRUCache({ max: 100, ttl: 60000 });
this.events = new EventEmitter();
this.initialize();
}
async initialize() {
await this.loadFeatureFlags();
this.listenForChanges();
}
async loadFeatureFlags() {
const flags = await this.db.execute(sql `SELECT name, enabled FROM hub_feature_flag`);
flags.forEach((flag) => this.cache.set(flag.name, flag.enabled));
}
async listenForChanges() {
const client = new Pool({ connectionString: process.env.DATABASE_URL });
const pgClient = await client.connect();
pgClient.query('LISTEN feature_flag_changes');
pgClient.on('notification', async () => {
await this.loadFeatureFlags();
this.events.emit('update');
});
}
isEnabled(flagName) {
return this.cache.get(flagName) ?? false;
}
onUpdate(callback) {
this.events.on('update', callback);
}
static setDatabaseUrl(url) {
process.env.DATABASE_URL = url;
}
}
export { FeatureFlagService };