-
Notifications
You must be signed in to change notification settings - Fork 1
/
FeatureWrapper.vue
80 lines (67 loc) · 2.14 KB
/
FeatureWrapper.vue
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
<template>
<slot v-if="isFeatureFlagEnabled === true" />
<slot v-else-if="isFeatureFlagEnabled === false" name="else" />
<slot v-else name="loading" />
</template>
<script setup lang="ts">
import { ref, onBeforeMount, onUnmounted, inject, type Ref } from "vue";
import {
ClientCacheState,
type IConfigCatClient,
type User,
} from "configcat-common";
const emits = defineEmits<{
(e: "flagValueChanged", newValue: boolean): void;
}>();
const props = defineProps<{
featureKey: string;
userObject?: User;
}>();
const isFeatureFlagEnabled: Ref<null | boolean> = ref(null);
const configCatClient =
inject<IConfigCatClient>("configCatClient") ??
(() => {
throw new Error("ConfigCatPlugin was not installed.");
})();
const configChangedHandler = () => {
const snapshot = configCatClient.snapshot();
const value = snapshot.getValue(props.featureKey, false, props.userObject);
if (isFeatureFlagEnabled.value !== value) {
isFeatureFlagEnabled.value = value;
emits("flagValueChanged", value);
}
};
onBeforeMount(() => {
const snapshot = configCatClient.snapshot();
const clientCacheState = snapshot.cacheState;
// Before the initial render of the component, initialize `isFeatureFlagEnabled`
// if the feature flag value is already available in the cache.
if (
clientCacheState == ClientCacheState.HasUpToDateFlagData ||
clientCacheState == ClientCacheState.HasLocalOverrideFlagDataOnly
) {
isFeatureFlagEnabled.value = snapshot.getValue(
props.featureKey,
false,
props.userObject
);
configCatClient.on("configChanged", configChangedHandler);
}
// Otherwise take the async path to get the feature flag value.
else {
configCatClient
.getValueAsync(props.featureKey, false, props.userObject)
.then((value) => {
const configChangedHandlerResult = configChangedHandler;
if (!configChangedHandlerResult) {
return;
}
isFeatureFlagEnabled.value = value;
configCatClient.on("configChanged", configChangedHandlerResult);
});
}
});
onUnmounted(() => {
configCatClient.off("configChanged", configChangedHandler);
});
</script>