budibase/packages/backend-core/src/features/index.ts

79 lines
2.0 KiB
TypeScript
Raw Normal View History

import env from "../environment"
import * as context from "../context"
2023-08-17 18:44:59 +02:00
export * from "./installation"
/**
* Read the TENANT_FEATURE_FLAGS env var and return an array of features flags for each tenant.
* The env var is formatted as:
* tenant1:feature1:feature2,tenant2:feature1
*/
2023-02-02 12:38:10 +01:00
export function buildFeatureFlags() {
if (!env.TENANT_FEATURE_FLAGS) {
return
}
const tenantFeatureFlags: Record<string, string[]> = {}
env.TENANT_FEATURE_FLAGS.split(",").forEach(tenantToFeatures => {
const [tenantId, ...features] = tenantToFeatures.split(":")
features.forEach(feature => {
if (!tenantFeatureFlags[tenantId]) {
tenantFeatureFlags[tenantId] = []
}
tenantFeatureFlags[tenantId].push(feature)
})
})
return tenantFeatureFlags
}
export function isEnabled(featureFlag: string) {
const tenantId = context.getTenantId()
const flags = getTenantFeatureFlags(tenantId)
2022-09-07 13:08:10 +02:00
return flags.includes(featureFlag)
}
export function getTenantFeatureFlags(tenantId: string) {
let flags: string[] = []
2023-02-02 12:38:10 +01:00
const envFlags = buildFeatureFlags()
if (envFlags) {
const globalFlags = envFlags["*"]
const tenantFlags = envFlags[tenantId] || []
// Explicitly exclude tenants from global features if required.
// Prefix the tenant flag with '!'
2023-02-02 12:38:10 +01:00
const tenantOverrides = tenantFlags.reduce(
(acc: string[], flag: string) => {
if (flag.startsWith("!")) {
let stripped = flag.substring(1)
acc.push(stripped)
}
return acc
},
[]
)
2022-09-07 13:08:10 +02:00
if (globalFlags) {
flags.push(...globalFlags)
}
if (tenantFlags.length) {
2022-09-07 13:08:10 +02:00
flags.push(...tenantFlags)
}
// Purge any tenant specific overrides
flags = flags.filter(flag => {
return tenantOverrides.indexOf(flag) == -1 && !flag.startsWith("!")
})
}
2022-09-07 13:08:10 +02:00
return flags
}
export enum TenantFeatureFlag {
LICENSING = "LICENSING",
GOOGLE_SHEETS = "GOOGLE_SHEETS",
USER_GROUPS = "USER_GROUPS",
2023-02-02 12:38:10 +01:00
ONBOARDING_TOUR = "ONBOARDING_TOUR",
}