Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature flag utils #27291

Draft
wants to merge 1 commit into
base: develop
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
135 changes: 135 additions & 0 deletions app/scripts/feature-flag.utils.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
import {
buildApiUrlAllFeatureFlags,
buildApiUrlSingleFeatureFlag,
getAllFeatureFlags,
getSingleFeatureFlag,
validateBuildType,
validateEnvironment,
} from './feature-flag.utils';

describe('feature-flag.utils', () => {
const mockBaseUrl = 'test';
const mockVersion = 'v1';

describe('buildApiUrlAllFeatureFlags', () => {
it('builds the correct URL with default parameters', () => {
const url = buildApiUrlAllFeatureFlags(mockBaseUrl);
console.log(url, mockBaseUrl);
expect(url).toBe(
`${mockBaseUrl}/${mockVersion}/flags?client=extension&distribution=main&environment=prod`,
);
});

it('builds the correct URL with custom parameters', () => {
const url = buildApiUrlAllFeatureFlags(
mockBaseUrl,
'flask',
'development',
);
expect(url).toBe(
`${mockBaseUrl}/${mockVersion}/flags?client=extension&distribution=flask&environment=dev`,
);
});
});

describe('buildApiUrlSingleFeatureFlag', () => {
it('builds the correct URL with default parameters', () => {
const url = buildApiUrlSingleFeatureFlag(mockBaseUrl, 'testFlag');
expect(url).toBe(
`${mockBaseUrl}/${mockVersion}/flags/testFlag?client=extension&distribution=main&environment=prod`,
);
});

it('builds the correct URL with custom parameters', () => {
const url = buildApiUrlSingleFeatureFlag(
mockBaseUrl,
'testFlag',
'flask',
'development',
);
expect(url).toBe(
`${mockBaseUrl}/${mockVersion}/flags/testFlag?client=extension&distribution=flask&environment=dev`,
);
});
});

describe('getAllFeatureFlags', () => {
it('fetches all feature flags successfully', async () => {
const mockResponse = [{ flag1: true }, { flag2: false }];
global.fetch = jest.fn().mockResolvedValue({
json: jest.fn().mockResolvedValue(mockResponse),
});

const flags = await getAllFeatureFlags(mockBaseUrl, 'main', 'prod');
expect(flags).toEqual({ flag1: true, flag2: false });
});

it('handles fetch error gracefully', async () => {
global.fetch = jest.fn().mockRejectedValue(new Error('Fetch error'));

const flags = await getAllFeatureFlags(mockBaseUrl, 'main', 'prod');
expect(flags).toEqual({});
});
});

describe('getSingleFeatureFlag', () => {
it('fetches a single feature flag successfully', async () => {
const mockResponse = { flag1: true };
global.fetch = jest.fn().mockResolvedValue({
json: jest.fn().mockResolvedValue(mockResponse),
});

const flag = await getSingleFeatureFlag(
mockBaseUrl,
'flag1',
'main',
'prod',
);
expect(flag).toEqual(mockResponse);
});

it('handles fetch error gracefully', async () => {
global.fetch = jest.fn().mockRejectedValue(new Error('Fetch error'));

const flag = await getSingleFeatureFlag(
mockBaseUrl,
'flag1',
'main',
'prod',
);
expect(flag).toEqual({});
});
});
describe('validateEnvironment', () => {
it('returns the correct environment for valid input', () => {
expect(validateEnvironment('prod')).toBe('prod');
expect(validateEnvironment('development')).toBe('dev');
});

it('returns default environment for invalid input', () => {
const consoleWarnSpy = jest.spyOn(console, 'warn').mockImplementation();
expect(validateEnvironment('invalid')).toBe('prod');
expect(consoleWarnSpy).toHaveBeenCalledWith(
'Invalid METAMASK_ENVIRONMENT value: invalid. Must be one of prod, development. Using default value: prod.',
);
consoleWarnSpy.mockRestore();
});
});

describe('validateBuildType', () => {
it('returns the correct build type for valid input', () => {
expect(validateBuildType('main')).toBe('main');
expect(validateBuildType('flask')).toBe('flask');
expect(validateBuildType('qa')).toBe('qa');
});

it('returns default build type for invalid input', () => {
const consoleWarnSpy = jest.spyOn(console, 'warn').mockImplementation();
expect(validateBuildType('invalid')).toBe('main');
expect(consoleWarnSpy).toHaveBeenCalledWith(
'Invalid METAMASK_BUILD_TYPE value: invalid. Must be one of main, flask, qa. Using default value: main.',
);
consoleWarnSpy.mockRestore();
});
});
});
110 changes: 110 additions & 0 deletions app/scripts/feature-flag.utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
// Description: Utility functions for fetching feature flags from the feature flag API.

const buildTypeOptions: string[] = ['main', 'flask', 'qa'];
const version = 'v1';

const environmentMapping: { [key: string]: string } = {
prod: 'prod',
development: 'dev',
};

export async function getAllFeatureFlags(
baseURL: string,
buildType: string,
environment: string,
): Promise<object> {
try {
const apiUrl = buildApiUrlAllFeatureFlags(baseURL, buildType, environment);
const response = await fetch(apiUrl);
const dataArray = await response.json();
const flagsObject = dataArray.reduce(
(
acc: { [key: string]: boolean },
current: { [key: string]: boolean },
) => ({ ...acc, ...current }),
{},
);

return flagsObject;
} catch (error) {
console.error('Failed to fetch feature flags:', error);
return {};
}
}

export async function getSingleFeatureFlag(
baseURL: string,
flagName: string,
buildType: string,
environment: string,
): Promise<object> {
try {
const apiUrl = buildApiUrlSingleFeatureFlag(
baseURL,
flagName,
buildType,
environment,
);
const response = await fetch(apiUrl);
const flagObject = await response.json();

return flagObject;
} catch (error) {
console.error('Failed to fetch feature flag:', error);
return {};
}
}

export function buildApiUrlAllFeatureFlags(
baseURL: string,
metamaskBuildType = 'main',
metamaskEnvironment = 'prod',
): string {
const client = 'extension';
const environment = validateEnvironment(metamaskEnvironment);
const buildType = validateBuildType(metamaskBuildType);

const url = `${baseURL}/${version}/flags?client=${client}&distribution=${buildType}&environment=${environment}`;

return url;
}

export function buildApiUrlSingleFeatureFlag(
baseURL: string,
flagName: string,
metamaskBuildType = 'main',
metamaskEnvironment = 'prod',
): string {
const client = 'extension';
const environment = validateEnvironment(metamaskEnvironment);
const buildType = validateBuildType(metamaskBuildType);

const url = `${baseURL}/${version}/flags/${flagName}?client=${client}&distribution=${buildType}&environment=${environment}`;

return url;
}

export function validateEnvironment(metamaskEnvironment: string): string {
const environment = environmentMapping[metamaskEnvironment];
if (!environment) {
console.warn(
`Invalid METAMASK_ENVIRONMENT value: ${metamaskEnvironment}. Must be one of ${Object.keys(
environmentMapping,
).join(', ')}. Using default value: prod.`,
);
return 'prod';
}
return environment;
}

export function validateBuildType(metamaskBuildType: string): string {
if (!buildTypeOptions.includes(metamaskBuildType)) {
console.warn(
`Invalid METAMASK_BUILD_TYPE value: ${metamaskBuildType}. Must be one of ${buildTypeOptions.join(
', ',
)}. Using default value: main.`,
);
return 'main';
}
return metamaskBuildType;
}
Loading