Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'feature-toggles' in functional components in JavaScript. Our advanced machine learning engine meticulously scans each line of code, cross-referencing millions of open source libraries to ensure your implementation is not just functional, but also robust and secure. Elevate your React applications to new heights by mastering the art of handling side effects, API calls, and asynchronous operations with confidence and precision.
module.exports = function errorHandler(err, req, res, next) {
/* If no error is defined, pass to next middleware. */
if (!util.isError(err)) return next();
let errResponse;
try {
errResponse = constructError(err);
if (!isApiError(err) && !isDbError(err) && !isCacheError(err)) {
if (/Route defined in Swagger specification.*/.test(err.message)) {
err.status = constants.httpStatus.NOT_ALLOWED;
} else if (err.name === 'Unauthorized') {
// Log and reject
err.status = constants.httpStatus.UNAUTHORIZED;
if (featureToggles.isFeatureEnabled('enableUnauthorizedActivityLogs')) {
const logObject = {
activity: 'unauthorized',
ipAddress: req.locals.ipAddress,
uri: req.url,
method: req.method,
};
// Add "request_id" if header is set by heroku.
if (req.request_id) logObject.request_id = req.request_id;
activityLog.printActivityLogString(logObject, 'unauthorized');
}
} else if (!err.status) {
err.status = constants.httpStatus.BAD_REQUEST;
}
}
getPerspective(req, res, next) {
/* Add userId to response to make it available from perspective page. */
res.cookie('userId', req.user.id, { maxAge: 1000 });
helper.cacheEnabled =
featureToggles.isFeatureEnabled('enableCachePerspective');
doGet(req, res, next, helper);
},
o.changed('value', true);
} else if (props.modelName === 'Perspective') {
/*
* Clone the object so that we can copy the new request object values
* in memory and validate them, instead of updating the db object in
* memory (which will prevent updating the object in db).
*/
const clonedObj = JSON.parse(JSON.stringify(o.get()));
// check the updated version of the perspective
helper.validateFilterAndThrowError(
Object.assign(clonedObj, requestBody)
);
}
if (featureToggles.isFeatureEnabled('requireHelpEmailOrHelpUrl') &&
props.requireAtLeastOneFields) {
try {
// check if at least one field present in db
validateAtLeastOneFieldPresent(o.get(), props.requireAtLeastOneFields);
} catch (err) {
// No field in db, check if at least one field present in request
validateAtLeastOneFieldPresent(req.body, props.requireAtLeastOneFields);
}
}
u.patchJsonArrayFields(o, requestBody, props);
u.patchArrayFields(o, requestBody, props);
return o.update(requestBody).then((o) => o.reload());
})
.then((limit) => {
res.set('X-RateLimit-Limit', limit.total);
res.set('X-RateLimit-Remaining', limit.remaining - 1);
res.set('X-RateLimit-Reset', limit.reset);
if (limit.remaining === 0) {
res.set('X-RateLimit-Remaining', 0);
var after = limit.reset - (Date.now() / 1000) | 0;
res.set('Retry-After', after);
if (req && featureToggles.isFeatureEnabled('enableLimiterActivityLogs')) {
const logObject = {
activity: 'limiter',
ipAddress: req.locals.ipAddress,
limit: `${config.max}/${config.duration}`,
method: req.method,
requestBytes: JSON.stringify(req.body).length,
responseBytes: 0,
token: req.headers.TokenName,
totalTime: `${Date.now() - req.timestamp}ms`,
uri: req.url,
user: req.headers.UserName,
};
// Add "request_id" if available
if (req.request_id) logObject.request_id = req.request_id;
.then((user) => {
// OK, we've got a user from the session!
// Get IP address and perspective name from socket handshake.
const ipAddress = ipAddressUtils.getIpAddressFromSocket(socket);
if (!ipAddress) {
throw new Error(DISCO_MSG);
}
/*
* Reject if feature enabled and x-forwarded-for has multiple ip
* addresses.
*/
if (toggle.isFeatureEnabled('rejectMultipleXForwardedFor') &&
ipAddress.indexOf(',') !== -1) {
throw new Error(DISCO_MSG);
}
if (conf.ipWhitelistService) {
ipWhitelistUtils.isWhitelisted(ipAddress)
.then((allowed) => {
if (!allowed) {
throw new Error('Access denied');
}
})
.catch((err) => {
throw new Error('Access denied');
});
} else {
rtUtils.isIpWhitelisted(ipAddress, ipWhitelist); // throws error
function persist() {
if (!featureToggles.isFeatureEnabled(constants.featureName)) {
return Promise.resolve(false);
}
return storeSampleToDb()
.catch((err) => {
// NO-OP
logger.error(err); // eslint-disable-line no-console
Promise.resolve(false);
});
} // persist
function storeSampleToCacheOrDb() {
const currentStatus = featureToggles.isFeatureEnabled(constants.featureName)
|| false;
return getPreviousStatus()
.then((prevState) => {
const previousStatus = (prevState == 'true') || false;
// set the previousStatus to the currentStatus
redisClient.setAsync(constants.previousStatusKey, currentStatus);
/*
* when the current status and the previous status do not match, actions
* needs to be taken based on the current status
*/
if (previousStatus !== currentStatus) {
/*
* call "popluate" when "enableRedisSampleStore" flag has been changed
if (!featureToggles.isFeatureEnabled('enableClockProcess')) {
require('./clock/index'); // eslint-disable-line global-require
}
/*
* Logging
*/
const processName = (process.env.DYNO ? process.env.DYNO + ':' : '') +
clusterProcessId;
if (conf.newRelicKey) {
require('newrelic');
}
if (featureToggles.isFeatureEnabled('enablePubsubStatsLogs')) {
const logPubSubStats = require('./realtime/pubSubStats').log;
setInterval(() => logPubSubStats(processName),
conf.pubSubStatsLoggingInterval);
}
// Log env vars. Only log once when there are multiple processes.
// Process id is 0 for a single process, 1-n for multiple throng workers.
if (clusterProcessId < 2) logEnvVars.log(process.env);
// Custom middleware to add process info to the request (for use in logging)
app.use((req, res, next) => {
// process id (0 for a single process, 1-n for multiple throng workers)
req.clusterProcessId = clusterProcessId;
// process name (dyno + process id)
req.process = processName;
function calculateJobPriority(prioritize, deprioritize, req) {
const jobPriority = {
high: 'high',
normal: 'normal',
low: 'low',
};
if (featureToggles.isFeatureEnabled('enableBullForBulkDelSubj')) {
// ranges from 1 (highest priority) to MAX_INT (lowest priority)
jobPriority.high = 1;
jobPriority.normal = 50;
jobPriority.low = 100;
}
// low=10, normal=0, medium=-5, high=-10, critical=-15
if (!req) return jobPriority.normal;
const ip = req.locals.ipAddress;
const un = req.headers.UserName || '';
const tn = req.headers.TokenName || '';
if (prioritize.includes(ip) ||
prioritize.includes(un) ||
prioritize.includes(tn)) return jobPriority.high;
if (deprioritize.includes(ip) ||
deprioritize.includes(un) ||
function registerHandlers(name, cli) {
cli.on('error', (err) => {
logger.error(`redisClientConnection=${name} event=error`, err);
return new Error(err);
});
if (featureToggles.isFeatureEnabled('enableRedisConnectionLogging')) {
cli.on('connect', () => {
logger.info(`redisClientConnection=${name} event=connect`);
});
cli.on('ready', () => {
logger.info(`redisClientConnection=${name} event=ready`);
});
cli.on('reconnecting', () => {
logger.info(`redisClientConnection=${name} event=reconnecting`);
});
}
} // registerHandlers