Skip to content

Commit

Permalink
feat[coral]: no-restricted-imports for page components (#160)
Browse files Browse the repository at this point in the history
- restrict page components to be only imported by router (except in test files)
- Introduce Ids to import restrict patterns. With Ids it
   will be easier to filter some specific pattern for a given
   file override.

Refers: #155
  • Loading branch information
SmuliS authored Oct 31, 2022
1 parent 22b9783 commit bf9bb65
Showing 1 changed file with 52 additions and 1 deletion.
53 changes: 52 additions & 1 deletion coral/.eslintrc.cjs
Original file line number Diff line number Diff line change
@@ -1,3 +1,47 @@
const NO_RESTRICTED_IMPORTS_RULES = ["error", {
patterns: [{
id: "DENY_PAGES_IMPORT",
group: ["src/pages*"],
message: "Pages should be only imported from '/src/router.tsx'"
}]
}]

function isObject(value) {
return typeof value === 'object' &&
!Array.isArray(value) &&
value !== null
}

const hasPatterns = (value) => isObject(value) && "patterns" in value;
const dropIdFromPatterns = (patterns) => patterns.map(({group, message}) => ({group, message}))

function filterPatternsByIds(patterns, ids) {
return patterns.filter(pattern => {
if ("id" in pattern) {
return !ids.includes(pattern.id)
}
return true
})
}

function strip_ids_from_no_restricted_imports(configuration) {
return configuration.map((rule) => {
if (hasPatterns(rule)) {
return {...rule, patterns: dropIdFromPatterns(rule.patterns)}
}
return rule
})
}

function filter_patterns_for_ids(configuration, ids) {
return configuration.map(rule => {
if (hasPatterns(rule)) {
return {...rule, patterns: dropIdFromPatterns(filterPatternsByIds(rule.patterns, ids))}
}
return rule
})
}

module.exports = {
"env": {
"browser": true,
Expand All @@ -11,6 +55,12 @@ module.exports = {
"prettier"
],
"overrides": [
{
"files": ["src/router.tsx", "src/pages/**/*.test.tsx"],
"rules": {
"no-restricted-imports": filter_patterns_for_ids(NO_RESTRICTED_IMPORTS_RULES, ["DENY_PAGES_IMPORT"])
}
}
],
"parser": "@typescript-eslint/parser",
"parserOptions": {
Expand All @@ -30,6 +80,7 @@ module.exports = {
"rules": {
"no-relative-import-paths/no-relative-import-paths": [
"error"
]
],
"no-restricted-imports": strip_ids_from_no_restricted_imports(NO_RESTRICTED_IMPORTS_RULES)
}
}

0 comments on commit bf9bb65

Please sign in to comment.