Skip to content

Commit

Permalink
Expose a nicer API for getting/setting feature flags on the current c…
Browse files Browse the repository at this point in the history
…ontext.
  • Loading branch information
samwho committed Aug 14, 2024
1 parent 08a56ef commit 0118593
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 9 deletions.
19 changes: 19 additions & 0 deletions packages/backend-core/src/context/mainContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -375,3 +375,22 @@ export function getCurrentContext(): ContextMap | undefined {
return undefined
}
}

export function getFeatureFlags<T extends Record<string, any>>(
key: string
): T | undefined {
const context = getCurrentContext()
if (!context) {
return undefined
}
return context.featureFlagCache?.[key] as T
}

export function setFeatureFlags(key: string, value: Record<string, any>) {
const context = getCurrentContext()
if (!context) {
return
}
context.featureFlagCache ??= {}
context.featureFlagCache[key] = value
}
11 changes: 2 additions & 9 deletions packages/backend-core/src/features/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,10 +130,7 @@ export class FlagSet<V extends Flag<any>, T extends { [key: string]: V }> {

async fetch(ctx?: UserCtx): Promise<FlagValues<T>> {
return await tracer.trace("features.fetch", async span => {
const requestContext = context.getCurrentContext()
const cachedFlags = requestContext?.featureFlagCache?.[this.setId] as
| FlagValues<T>
| undefined
const cachedFlags = context.getFeatureFlags<FlagValues<T>>(this.setId)
if (cachedFlags) {
span?.addTags({ fromCache: true })
return cachedFlags
Expand Down Expand Up @@ -252,11 +249,7 @@ export class FlagSet<V extends Flag<any>, T extends { [key: string]: V }> {
}
}

if (requestContext) {
requestContext.featureFlagCache ??= {}
requestContext.featureFlagCache[this.setId] = flagValues
}

context.setFeatureFlags(this.setId, flagValues)
for (const [key, value] of Object.entries(flagValues)) {
tags[`flags.${key}.value`] = value
}
Expand Down

0 comments on commit 0118593

Please sign in to comment.