Created
February 8, 2023 09:00
-
-
Save jede/cce91a376384fef466d70c254ad73b02 to your computer and use it in GitHub Desktop.
Script to check that inverses are set and match in Ember.js.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* eslint-disable node/no-extraneous-require */ | |
const babelParser = require('@babel/parser') | |
const _ = require('lodash') | |
const fs = require('fs') | |
const path = require('path') | |
const DIR = './app/models' | |
const files = fs.readdirSync(DIR).filter((f) => f.match(/\.js$/)) | |
const parsedModels = {} | |
for (const file of files) { | |
const data = fs.readFileSync(path.join(DIR, file)) | |
const name = file.replace(/\.js$/, '') | |
parsedModels[name] = babelParser.parse(data.toString(), { sourceType: 'module', plugins: ['decorators'] }) | |
} | |
const models = {} | |
for (const [name, parsed] of Object.entries(parsedModels)) { | |
const declaration = | |
parsed.program.body.find((n) => n.type === 'ClassDeclaration') ?? | |
parsed.program.body.find((n) => n.type === 'ExportDefaultDeclaration').declaration | |
const rels = declaration?.body.body.filter((n) => | |
n.decorators?.some((d) => d.expression?.callee?.name === 'hasMany' || d.expression?.callee?.name === 'belongsTo') | |
) | |
models[name] = rels.map((rel) => { | |
const model = rel.decorators[0].expression.arguments[0].value | |
const inverseProp = rel.decorators[0].expression.arguments[1]?.properties.find( | |
({ key: { name } }) => name === 'inverse' | |
) | |
const inverse = inverseProp?.value.value | |
const inverseIsNull = !inverse && inverseProp && inverseProp.value.type === 'NullLiteral' | |
return { name: rel.key.name, inverse, inverseIsNull, model } | |
}) | |
} | |
for (const [name, rels] of Object.entries(models)) { | |
for (const { name: relName, inverse, inverseIsNull, model } of rels) { | |
if (inverse) { | |
const inverseModelRels = models[_.kebabCase(model)] | |
if (inverseModelRels) { | |
const invRel = inverseModelRels.find(({ name }) => name === inverse) | |
if (invRel) { | |
if (_.kebabCase(invRel.model) !== name) { | |
console.log(name, relName, 'wrongname') | |
} | |
if (invRel.inverse !== relName) { | |
console.log(name, relName, 'wronginverse') | |
} | |
} else { | |
console.log(name, relName, 'nomatch') | |
} | |
} else { | |
console.log(name, relName, 'nomodel') | |
} | |
} else if (inverseIsNull) { | |
// console.log(name, relName, 'null') | |
} else { | |
console.log(name, relName, 'missing') | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment