@transferwise/eslint-plugin
Version:
TransferWise ESLint plugin
75 lines (64 loc) • 2.19 kB
JavaScript
/**
* @fileoverview Ensures getServerSideProps is within the pages directory
* @author fergusjordantw
*/
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
module.exports = {
meta: {
docs: {
description:
"Declaring & exporting getServerSideProps outside of the Next page itself impedes Next's ability to strip code that is only used on server side",
category: 'Best Practices',
recommended: false,
},
fixable: null,
schema: [],
},
create(context) {
const sourceCode = context.sourceCode ?? context.getSourceCode();
const filename = context.filename ?? context.getFilename();
function checkExportedName(node) {
const name = node?.name;
if (name !== 'getServerSideProps') {
return;
}
const isInPagesDirectory = filename.includes('pages');
if (!isInPagesDirectory) {
context.report({
node,
message:
'getServerSideProps can only be exported from the pages directory',
});
}
}
function checkExportedNameFromNode(node) {
const declaration = node.declaration;
if (declaration) {
if (
declaration.type === 'FunctionDeclaration' ||
declaration.type === 'ClassDeclaration'
) {
checkExportedName(declaration.id);
} else if (declaration.type === 'VariableDeclaration') {
(sourceCode.getDeclaredVariables ? sourceCode.getDeclaredVariables(declaration, context) : context.getDeclaredVariables())
.map((v) => v.defs.find((d) => d.parent === declaration))
.map((d) => d.name)
.forEach(checkExportedName);
}
} else {
node.specifiers.map((s) => s.exported).forEach(checkExportedName);
}
}
return {
ExportAllDeclaration(node) {
if (node.exported) {
checkExportedName(node.exported);
}
},
ExportNamedDeclaration: checkExportedNameFromNode,
ExportDefaultDeclaration: checkExportedNameFromNode,
};
},
};