UNPKG

flagmint-vuejs-feature-flags

Version:

A Vue.js SDK for managing feature flags in Flagmint applications, supporting both Vue 2 and Vue 3.

71 lines (69 loc) 2.58 kB
const useFlagsMixin = { data() { return { isFlagReady: false, flagClient: null, flags: {}, // Reactive snapshot — updated on every push _flagmintUnsubscribe: null, // Holds the unsubscribe function }; }, created() { if (this.$flagmintReady) { // Already ready at creation time (e.g. deferred component) this.flagClient = this.$flagmint; this.isFlagReady = true; this._startFlagSubscription(); } else if (typeof this.$flagmintInit === 'function') { // Not ready yet — call init and wait this.$flagmintInit().then((client) => { this.flagClient = client; this.isFlagReady = true; this._startFlagSubscription(); }); } else { // Watch for $flagmintReady to become true (plugin provided it as a reactive ref) this.$watch('$flagmintReady', (val) => { if (val) { this.flagClient = this.$flagmint; this.isFlagReady = true; this._startFlagSubscription(); } }); } }, beforeDestroy() { // Clean up subscription — never call destroy() on the shared client if (this._flagmintUnsubscribe) { this._flagmintUnsubscribe(); this._flagmintUnsubscribe = null; } }, methods: { _startFlagSubscription() { const client = this.flagClient; if (!client || this._flagmintUnsubscribe) return; // subscribe() calls back immediately with current flags, // then on every WebSocket push — updates this.flags reactively this._flagmintUnsubscribe = client.subscribe((updatedFlags) => { this.flags = updatedFlags; }); }, getFlag(key, fallback) { var _a; // Reads from reactive this.flags — re-renders on every push return ((_a = this.flags[key]) !== null && _a !== void 0 ? _a : fallback); }, async updateFlagmintContext(context) { if (this.flagClient && typeof this.flagClient.updateContext === 'function') { await this.flagClient.updateContext(context); } else { console.warn('[Flagmint] updateFlagmintContext called before client was ready.'); } } }, }; export { useFlagsMixin };