ESLint's Restricted syntax and Contentful Migrations
At work we are using Contentful as a headless CMS, and also Adobe DAM as an asset storage platform. Both platforms support localization, but we only want to have it enabled in the DAM as that makes the digital production team's life easier.
However some Contentful models ended up having linked DAM assets fields set to localized: true
, which means that the content editor team now needs to link the asset essentially twice, so that's not good.
How do we ensure, that all new changes to the Contentful schema are not going to suffer from the same problem?
ESLint no-restricted-syntax
rule to the rescue.
Essentially a migration looks like this
function(migration) {
migration
.createContentType("coolImageStorage")
.createField("coolImage", {
type: "Link",
linkType: "Entry",
localized: true, // <- here's what we want to avoid
validations: [{ linkContentType: "damAsset" }]
})
}
A following rule can detect when a field is created as a damAsset
link, and also has localized
set to true
.
CallExpression:has(Property[key.name=localized][value.value=true]) Property[key.name=linkContentType]:has(Literal[value=damAsset])
Wire it up into the .eslintrc
file as follows:
{
"rules": {
"no-restricted-syntax": ["error", {
"selector": "CallExpression:has(Property[key.name=localized][value.value=true]) Property[key.name=linkContentType]:has(Literal[value=damAsset])",
"message": "DAM Asset should not be localized"
}]
}
}
and marvel at how technology is sometimes able to save us from ourselves.
AST Explorer with babel-eslint
parser and ESLint v8
transform can help you poke around at the AST to figure out how to wire up these rules.