Skip to content

Commit

Permalink
fix: edge case on context value where trim is not a function (#648)
Browse files Browse the repository at this point in the history
  • Loading branch information
nunogois committed Jul 23, 2024
1 parent e61e55a commit 2ccb88a
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 2 deletions.
3 changes: 2 additions & 1 deletion src/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ export function createFallbackFunction(
}

export function resolveContextValue(context: Context, field: string): string | undefined {
return context[field]?.toString() ?? context.properties?.[field]?.toString();
const contextValue = context[field] ?? context.properties?.[field];
return contextValue !== undefined && contextValue !== null ? String(contextValue) : undefined;
}

export function safeName(str: string = '') {
Expand Down
5 changes: 4 additions & 1 deletion src/strategy/strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,11 +93,14 @@ const SemverOperator = (constraint: Constraint, context: Context) => {
const { contextName, operator } = constraint;
const value = constraint.value as string;
const contextValue = resolveContextValue(context, contextName);
if (!contextValue || !isStrictSemver(contextValue)) {
if (!contextValue) {
return false;
}

try {
if (!isStrictSemver(contextValue)) {
return false;
}
if (operator === Operator.SEMVER_EQ) {
return semverEq(contextValue, value);
}
Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -602,3 +602,24 @@ test('should be enabled for missing field when NOT_IN', (t) => {
// @ts-expect-error
t.true(strategy.isEnabledWithConstraints(params, context, constraints));
});

test('should gracefully handle version with custom toString that does not return string', (t) => {
const strategy = new Strategy('test', true);
const params = {};
const constraints = [{ contextName: 'version', operator: 'SEMVER_EQ', value: '1.2.2' }];
const context = {
environment: 'dev',
properties: { version: { toString: () => 122 } },
};

try {
// @ts-expect-error
const enabled = strategy.isEnabledWithConstraints(params, context, constraints);
t.true(enabled || !enabled); // This will pass if no error is thrown
} catch (error: unknown) {
// @ts-expect-error
t.fail(`Threw error: ${error.message}`);
}

t.pass();
});

0 comments on commit 2ccb88a

Please sign in to comment.