Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/scmi 124866 [Domain models initiative] private attribute lint rule #1789

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
4 changes: 3 additions & 1 deletion packages/eslint-plugin-sui/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ const SerializeDeserialize = require('./rules/serialize-deserialize.js')
const CommonJS = require('./rules/commonjs.js')
const Decorators = require('./rules/decorators.js')
const LayersArch = require('./rules/layers-architecture.js')
const PrivateAttributesModel = require('./rules/private-attributes-model.js')

// ------------------------------------------------------------------------------
// Plugin Definition
Expand All @@ -15,6 +16,7 @@ module.exports = {
'serialize-deserialize': SerializeDeserialize,
commonjs: CommonJS,
decorators: Decorators,
'layers-arch': LayersArch
'layers-arch': LayersArch,
'private-attributes-model': PrivateAttributesModel
}
}
107 changes: 107 additions & 0 deletions packages/eslint-plugin-sui/src/rules/private-attributes-model.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
/**
* @fileoverview ensure domain model have a private attributes and each attribute has a getter
*/
'use strict'

const dedent = require('string-dedent')
const path = require('path')

// ------------------------------------------------------------------------------
// Rule Definition
// ------------------------------------------------------------------------------

/** @type {import('eslint').Rule.RuleModule} */
module.exports = {
meta: {
type: 'suggestion',
docs: {
description: 'Ensure domain models have all attributes as private and each attribute has a getter',
recommended: false,
url: 'https://github.mpi-internal.com/scmspain/es-td-agreements/blob/master/30-Frontend/00-agreements'
},
fixable: null,
schema: [],
messages: {
attributeHasToBePrivate: dedent`
If your class is a domain model (Value Object or Entity), you have to define all attributes as private with #.
`,
privateAttributeHasToHaveGetter: dedent`
If your class is a domain model (Value Object or Entity), you have to define a getter for the attribute #{{attributeName}}.
You can define a native getter (get {{attributeName}}) or a custom getter ({{customGetterName}}).
`
}
},

create(context) {
const filePath = context.getFilename()
const relativePath = path.relative(context.getCwd(), filePath)

// Check if the file is inside requierd folders (useCases, services, repositories, ...)
const valueObjectPattern = /valueObjects|valueobjects|ValueObjects|Valueobjects/i
const isValueObjectPath = valueObjectPattern.test(relativePath)

const entityPattern = /entity|Entity/i
const isEntityPath = entityPattern.test(relativePath)

return {
ClassDeclaration(node) {
const className = node.id?.name ?? ''
const allowedWords = ['VO', 'ValueObject', 'Entity']
Copy link
Contributor

@oriolpuig oriolpuig Jul 22, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a good approach and this rule will cover a lot of cases, but it will not check classes without names but under the correct place (valueObjects or entities folders).

To achieve that, with the lines below, you can check if the file is inside those folders and run this rule inside them too.

    const filePath = context.getFilename()
    const relativePath = path.relative(context.getCwd(), filePath)

    // Check if the file is inside the requierd folders (entities, services, repositories, ...)
    const entitiesPattern = /entities|Entities/i
    const isEntityPath = entitiesPattern.test(relativePath)

    // ... same with value objects

See this PR lines, and follow the code to understand.

I suggest you detect different cases in our code base and run it there to see if this rule is working fine in different scenarios.

const isDomainModelName = allowedWords.some(allowWord => className.includes(allowWord))

if (!isDomainModelName && !isValueObjectPath) return
if (!isDomainModelName && !isEntityPath) return

// Check if all attributes are public
const publicAttributes = node?.body?.body?.filter(node => {
return (
node.type === 'PropertyDefinition' &&
node.key?.type === 'Identifier' &&
node.value?.type !== 'ArrowFunctionExpression'
)
})

publicAttributes.forEach(attribute => {
context.report({
node: attribute,
messageId: 'attributeHasToBePrivate'
})
})

// Check if a private attribute has a public accessor
const privateAttributes = node.body.body.filter(node => {
return node.type === 'PropertyDefinition' && node.key?.type === 'PrivateIdentifier'
})
const classMethods = node.body.body.filter(node => {
return node.type === 'MethodDefinition' || node.value?.type === 'ArrowFunctionExpression'
})

privateAttributes.forEach(attribute => {
let hasGetter = false
const customGetterName = `get${attribute.key.name.charAt(0).toUpperCase()}${attribute.key.name.slice(1)}`

classMethods.forEach(method => {
const existNativeGetterWithAttributeKey =
method?.key?.name === attribute?.key?.name && method?.kind === 'get'
const existCustomGetterWithAttributeKey = method?.key?.name === customGetterName

if (existNativeGetterWithAttributeKey || existCustomGetterWithAttributeKey) {
hasGetter = true
}
})

if (!hasGetter) {
context.report({
node: attribute,
messageId: 'privateAttributeHasToHaveGetter',
data: {
attributeName: attribute?.key?.name,
customGetterName
}
})
}
})
}
}
}
}
3 changes: 2 additions & 1 deletion packages/sui-lint/eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,8 @@ module.exports = {
rules: {
'sui/factory-pattern': RULES.WARNING,
'sui/serialize-deserialize': RULES.WARNING,
'sui/decorators': RULES.WARNING
'sui/decorators': RULES.WARNING,
'sui/private-attributes-model': RULES.WARNING
}
},
{
Expand Down