@lokalise/fastify-extras
Version:
Opinionated set of fastify plugins, commonly used in Lokalise
58 lines • 2.12 kB
JavaScript
import * as path from 'node:path';
import * as process from 'node:process';
import { SplitFactory } from '@splitsoftware/splitio';
import fp from 'fastify-plugin';
const DISABLED_TREATMENT = 'control';
export class SplitIOFeatureManager {
isEnabled;
splitIOClient;
constructor(isSplitIOEnabled, apiKey, debugMode, localhostFilePath) {
if (isSplitIOEnabled) {
const factory = SplitFactory({
core: {
authorizationKey: localhostFilePath ? 'localhost' : apiKey,
},
features: localhostFilePath ? path.join(process.cwd(), localhostFilePath) : undefined,
debug: debugMode,
});
this.splitIOClient = factory.client();
}
this.isEnabled = isSplitIOEnabled;
}
async init() {
await this.splitIOClient?.ready();
}
getTreatment(key, splitName, attributes) {
return this.splitIOClient?.getTreatment(key, splitName, attributes) ?? DISABLED_TREATMENT;
}
getTreatmentWithConfig(key, splitName, attributes) {
return (this.splitIOClient?.getTreatmentWithConfig(key, splitName, attributes) ?? {
treatment: DISABLED_TREATMENT,
config: null,
});
}
track(key, trafficType, eventType, value, properties) {
return this.splitIOClient?.track(key, trafficType, eventType, value, properties) ?? false;
}
async shutdown() {
if (!this.isEnabled) {
return;
}
await this.splitIOClient?.destroy();
}
}
async function plugin(fastify, opts) {
const manager = new SplitIOFeatureManager(opts.isEnabled, opts.apiKey, opts.debugMode, opts.localhostFilePath);
fastify.decorate('splitIOFeatureManager', manager);
if (opts.isEnabled) {
fastify.addHook('onClose', async () => {
await manager.shutdown();
});
}
await manager.init();
}
export const splitIOFeatureManagerPlugin = fp(plugin, {
fastify: '5.x',
name: 'split-io-feature-manager-plugin',
});
//# sourceMappingURL=splitIOFeatureManagerPlugin.js.map