All questions

Wrapping evaluate in a Vue composable for a feature flag

Asked by ahmed_k on

Aahmed_k

I like small reusable helpers, so I want a Vue composable that evaluates a CQL condition to gate a feature and returns a safe default if the call fails.

Two questions: how do I write the evaluate call itself, and what should I guard against so a failure or a bad query does not leave the flag in a weird state?

Was this helpful?

2 answers

Ggustavo_m

The core is one call plus a guard. Evaluate the condition and catch to a safe default so a failure resolves to off rather than throwing:

export function useFlag(query: string) {    const enabled = ref(false);
    onMounted(async () => {        enabled.value = await croct            .evaluate(query)            .catch(() => false);    });
    return {enabled};}

Then const {enabled} = useFlag('user is returning'). The .catch(() => false) is the important bit, it means a network hiccup gates the feature off instead of crashing the component.

Was this helpful?
Nnina_p

Two behaviours to keep in mind when you write the conditions. CQL is english-like and case-insensitive, and undefined variables evaluate to false by design, so if you reference something that is not set the whole condition just resolves to false rather than erroring. That is usually what you want for a flag, but it also means a typo in a variable name silently gates the feature off.

Also there is a size ceiling: queries run from 1 to 500 characters, and an oversized one raises a "Too complex query" error. If you are composing long conditions programmatically, keep an eye on the length.

One aside worth mentioning if the flag drives visible UI: resolving it on the server avoids a client-side flash of the wrong state, same reasoning as content slots.

Was this helpful?
Aahmed_k

Good, the undefined-to-false behaviour is exactly the default I wanted. Shipping the composable with the catch guard. Thanks both.

Still have questions?