A feature toggle library for enabling or disabling features in your application based on configuration.
npm install feature-toggle
To initialize the feature toggle service, you need to provide a configuration source. This can be a URL, a file path, or a configuration object.
import { FeatureToggleService } from './service/feature-toggle.service.js';
const configSource = 'path/to/config.json'; // or a URL or a configuration object
const options = {
cacheDuration: 600000, // 10 minutes
headers: {
'Authorization': 'Bearer token'
},
errorHandler: (error) => console.error(error)
};
const service = FeatureToggleService.getInstance();
await service.initialize(configSource, options);
Use the middleware to protect routes based on feature toggles.
import express from 'express';
import { featureCheckMiddleware } from './middleware/feature-toggle.middleware.js';
const app = express();
app.use('/api/feature', featureCheckMiddleware('moduleName', 'submoduleName', 'featureName'), (req, res) => {
res.send('Feature is enabled');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Use the React hook to check feature toggles in functional components.
import React from 'react';
import { useFeatureToggle } from './hook/useFeatureToggle.js';
const configSource = 'path/to/config.json';
const MyComponent = () => {
const { error, loading } = useFeatureToggle(configSource);
if (loading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return <div>Feature Toggle Initialized</div>;
};
Use the React component to conditionally render based on feature toggles.
import React from 'react';
import { FeatureToggle } from './components/FeatureToggle.js';
const MyComponent = () => (
<FeatureToggle moduleName="moduleName" submoduleName="submoduleName" featureName="featureName" fallback={<div>Feature Disabled</div>}>
<div>Feature Enabled</div>
</FeatureToggle>
);
Returns the singleton instance of the FeatureToggleService
.
Initializes the feature toggle service with the provided configuration source and options.
Checks if a feature is enabled based on the module, submodule, and feature name.
Sets the configuration manually.
Returns the current configuration.
Returns an Express middleware function that checks if a feature is enabled.
A React hook that initializes the feature toggle service and returns the loading and error state.
A React component that conditionally renders its children based on the feature toggle state.
Props:
-
moduleName
: The name of the module. -
submoduleName
: The name of the submodule. -
featureName?
: The name of the feature (optional). -
children
: The content to render if the feature is enabled. -
fallback?
: The content to render if the feature is disabled (optional).
The configuration should follow this format:
{
"modules": {
"moduleName": {
"enabled": true,
"submodules": {
"submoduleName": {
"enabled": true,
"features": {
"featureName": true
}
}
}
}
}
}
MIT