1 import { isObject, isString } from "@medusajs/utils"
2 import { FeatureFlagsResponse, IFlagRouter } from "./types"
3
4 export class FlagRouter implements IFlagRouter {
5 private readonly flags: Record<string, boolean | Record<string, boolean>> = {}
6
7 constructor(flags: Record<string, boolean | Record<string, boolean>>) {
8 this.flags = flags
9 }
10
11 /**
12 * Check if a feature flag is enabled.
13 * There are two ways of using this method:
14 * 1. `isFeatureEnabled("myFeatureFlag")`
15 * 2. `isFeatureEnabled({ myNestedFeatureFlag: "someNestedFlag" })`
16 * We use 1. for top-level feature flags and 2. for nested feature flags. Almost all flags are top-level.
17 * An example of a nested flag is workflows. To use it, you would do:
18 * `isFeatureEnabled({ workflows: Workflows.CreateCart })`
19 * @param flag - The flag to check
20 * @return {boolean} - Whether the flag is enabled or not
21 */
22 public isFeatureEnabled(
23 flag: string | string[] | Record<string, string>
24 ): boolean {
25 if (isObject(flag)) {
26 const [nestedFlag, value] = Object.entries(flag)[0]
27 if (typeof this.flags[nestedFlag] === "boolean") {
28 return this.flags[nestedFlag] as boolean
29 }
30 return !!this.flags[nestedFlag]?.[value]
31 }
32
33 const flags = (Array.isArray(flag) ? flag : [flag]) as string[]
34 return flags.every((flag_) => {
35 if (!isString(flag_)) {
36 throw Error("Flag must be a string an array of string or an object")
37 }
38 return !!this.flags[flag_]
39 })
40 }
41
42 /**
43 * Sets a feature flag.
44 * Flags take two shapes:
45 * `setFlag("myFeatureFlag", true)`
46 * `setFlag("myFeatureFlag", { nestedFlag: true })`
47 * These shapes are used for top-level and nested flags respectively, as explained in isFeatureEnabled.
48 * @param key - The key of the flag to set.
49 * @param value - The value of the flag to set.
50 * @return {void} - void
51 */
52 public setFlag(
53 key: string,
54 value: boolean | { [key: string]: boolean }
55 ): void {
56 if (isObject(value)) {
57 const existing = this.flags[key]
58
59 if (!existing) {
60 this.flags[key] = value
61 return
62 }
63
64 this.flags[key] = { ...(this.flags[key] as object), ...value }
65 return
66 }
67
68 this.flags[key] = value
69 }
70
71 public listFlags(): FeatureFlagsResponse {
72 return Object.entries(this.flags || {}).map(([key, value]) => ({
73 key,
74 value,
75 }))
76 }
77 }