import { Rule, SchematicContext, Tree } from '@angular-devkit/schematics'; import { ModelField, ModelRelation, ClassRelationEnum, Model, AngularFieldType } from '@vmfvmf/ywtc-lib'; import { error } from "console"; import { camelize, classify, dasherize, underscore } from '@angular-devkit/core/src/utils/strings'; import { getModelById, getPrjSrd } from '../../router.gen'; export function gen(model: Model): Rule { return (tree: Tree, _context: SchematicContext) => { const dbScriptsPath = `ywtc-output/${getPrjSrd().prjNDashd}-frontend/cypress/src/db-scripts.ts`; const updatedDbScriptse = updateDbScripts(getFileContent(tree, dbScriptsPath)!, model); tree.overwrite(dbScriptsPath, updatedDbScriptse); return tree; }; } function getFileContent(tree: Tree, fileName: string) { if (!tree.exists(fileName)) { throw new Error(`File: ${fileName} NOT FOUND.`) } return tree.read(fileName)?.toString(); } function updateDbScripts(content: string, model: Model) { const jtcImports = '/*JTCIMPORTS*/'; const jtcAdd = '/*JTCADD*/'; const jtcAddRel = '/*JTCADDREL*/'; if (content.includes(jtcImports) && content.includes(jtcAdd) && content.includes(jtcAddRel)) { let nameDashed = getPrjSrd().mdlNDashd!; let nameClassed = getPrjSrd().mdlNClasd!; let nameUpper = getPrjSrd().mdlNCamld.toUpperCase(); let nameUndrld = getPrjSrd().mdlNUndes!; let imports = [ `import { I${classify(model.name)} } from 'src/app/${getPrjSrd().prjNDashd}-frontend/${nameDashed}/${nameDashed}';`, `import { ${nameUpper}_FACTORY } from 'cypress/fixtures/${nameDashed}-factory';` ]; let hlp = nameDashed[0]; if (hlp === 'i') hlp = 'j'; let oToOne: string[] = []; model.relations .filter(rel => (rel.relation == ClassRelationEnum.OneToOne) || (rel.relation == ClassRelationEnum.ManyToOne)) .forEach(relOneToOne => oToOne.push(relOneToOne.name + '_id')); model.othersideRelations .filter(rel => rel.relation === ClassRelationEnum.OneToMany) .forEach(rel => oToOne.push(underscore(getModelById(rel.modelId).name) + '_id')) let oToOneStr = oToOne.join(","); oToOneStr = oToOneStr ? ',' + oToOneStr : ''; const oToOneValueStr = oToOneStr ? ', ' + oToOne.map(() => '${i+1}').join(',') : ''; let addScript = `INSERT_${nameUpper}: \`INSERT INTO ${getPrjSrd().dbName}.${nameUndrld}\n` + ` (${model.fields.map(f => dasherize(f.name).replace('-', '_')) + oToOneStr}) VALUES\n` + ' ${\n' + ` ${nameUpper}_FACTORY.SEARCH_POOL\n` + ` .map((${hlp}: I${nameClassed}, i:number) => {\n` + ` return \`(${model.fields.map(f => fieldMap(f, hlp)).join(',')+oToOneValueStr})\`;\n` + ' })\n' + " .join(', ')\n" + ' };`,\n'; let addScriptRel = new Array(); model.relations .filter((rel: ModelRelation) => [ClassRelationEnum.ManyToMany].includes(rel.relation)) .forEach((rel: ModelRelation) => { let relNameDashed = dasherize(rel.toModelName); let relNameUndes = relNameDashed.replace('-', '_'); let relNameCamed = camelize(relNameDashed); let relHlp = relNameDashed[0]; addScriptRel.push( `INSERT_${nameUpper}_${relNameUndes.toUpperCase()}: \`INSERT INTO ${getPrjSrd().dbName}.rel_${nameUndrld}_${relNameUndes}\n` + ` (${nameUpper}_id, ${relNameUndes}_id) VALUES\n` + ' ${\n' + ` ${nameUpper}_FACTORY.SEARCH_POOL\n` + ` .map((${hlp}: I${nameClassed}, i${hlp}: number) => ${hlp}.${relNameCamed}sIds?.map((${relHlp}: number) => \`(\${i${hlp}+1}, \${${relHlp}})\`).join(', '))\n` + " .join(', ')\n" + ' };`,\n' )}); content = content.replace(jtcImports, `${imports.join('\n')}\n${jtcImports}`); content = content.replace(jtcAdd, `${addScript}\n${jtcAdd}`); content = content.replace(jtcAddRel, `${addScriptRel.join('\n')}\n${jtcAddRel}`); } else { throw error(`The db-scripts.ts file is missing ${jtcImports} or ${jtcAdd}!!!`); } return content; } function fieldMap(f: ModelField, hlp: string) { switch(f.angularType) { case AngularFieldType.DATE: return "'${pipeTransform.date(" + hlp + "." + f.name + ", 'yyyy-MM-dd')}'"; case AngularFieldType.DATETIME: return "'${" + hlp + "." + f.name + "?.toISOString().replace('Z', '')}'"; case AngularFieldType.BOOLEAN: return "'${" + hlp + "." + f.name + "? 1 : 0 }'"; } return "'${" + hlp + '.' + f.name + "}'"; }