eslint-plugin-green
Version:
ESLint plugin for evaluating and promoting green coding practices
68 lines (67 loc) • 3.04 kB
JavaScript
;
const rule = {
meta: {
type: 'suggestion',
docs: {
description: 'Enforce efficient network request patterns',
category: 'Network',
recommended: true,
},
schema: [], // no options
},
create(context) {
const fetchCalls = new Map();
return {
CallExpression(node) {
var _a;
if (node.callee.type === 'Identifier' && node.callee.name === 'fetch') {
// Track duplicate fetch calls
if (((_a = node.arguments[0]) === null || _a === void 0 ? void 0 : _a.type) === 'Literal') {
const url = node.arguments[0].value;
fetchCalls.set(url, (fetchCalls.get(url) || 0) + 1);
if (fetchCalls.get(url) > 1) {
context.report({
node,
message: 'Consider caching the fetch response or using a request deduplication mechanism'
});
}
}
// Check for missing error handling
const parent = context.getAncestors().pop();
if ((parent === null || parent === void 0 ? void 0 : parent.type) !== 'CatchClause' && !(parent === null || parent === void 0 ? void 0 : parent.type.includes('Catch'))) {
context.report({
node,
message: 'Add error handling to fetch calls to handle network failures gracefully'
});
}
}
// Check for XMLHttpRequest usage
if (node.callee.type === 'MemberExpression') {
const callee = node.callee;
if (callee.property.type === 'Identifier') {
const methodName = callee.property.name;
if (methodName === 'open' && callee.object.type === 'Identifier' &&
callee.object.name === 'XMLHttpRequest') {
context.report({
node,
message: 'Consider using fetch instead of XMLHttpRequest for better performance and energy efficiency'
});
}
}
}
},
'Program:exit'() {
// Report on excessive API calls to the same endpoint
fetchCalls.forEach((count, url) => {
if (count > 3) {
context.report({
loc: { line: 1, column: 0 },
message: `Multiple calls (${count}) to ${url} detected. Consider implementing request batching or caching`
});
}
});
}
};
}
};
module.exports = rule;