UNPKG

generator-begcode

Version:

Spring Boot + Angular/React/Vue in one handy generator

89 lines (88 loc) 2.88 kB
import { upperFirst } from 'lodash-es'; import { merge } from '../utils/object-utils.js'; import { shouldWriteEntityTableName } from '../jhipster/index.js'; export default class JDLEntity { name; tableName; fields; comment; annotations; constructor(args) { const merged = merge(defaults(), args); if (!merged.name) { throw new Error('The entity name is mandatory to create an entity.'); } this.name = merged.name; this.tableName = merged.tableName; this.fields = merged.fields ?? {}; this.comment = merged.comment; this.annotations = merged.annotations ?? {}; } addFields(fields = []) { fields.forEach(field => this.addField(field)); } addField(field) { if (!field) { throw new Error("Can't add nil field to the JDL entity."); } this.fields[field.name] = field; } forEachField(functionToApply) { if (!functionToApply) { throw new Error('A function must be passed to iterate over fields'); } Object.values(this.fields).forEach(functionToApply); } toString() { let stringifiedEntity = ''; if (this.comment) { stringifiedEntity += `/**\n${this.comment .split('\n') .map(line => ` * ${line}\n`) .join('')} */\n`; } Object.entries(this.annotations).forEach(([key, value]) => { key = upperFirst(key); if (value === true) { stringifiedEntity += `@${key}\n`; } else if (typeof value === 'string') { stringifiedEntity += `@${key}("${value}")\n`; } else { stringifiedEntity += `@${key}(${value})\n`; } }); stringifiedEntity += `entity ${this.name}`; if (this.tableName && shouldWriteEntityTableName(this.name, this.tableName)) { stringifiedEntity += ` (${this.tableName})`; } if (Object.keys(this.fields).length !== 0) { stringifiedEntity += ` {\n${formatFieldObjects(this.fields)}\n}`; } return stringifiedEntity; } } function defaults() { return { fields: {}, annotations: {}, }; } function formatFieldObjects(jdlFieldObjects) { let string = ''; Object.keys(jdlFieldObjects).forEach(jdlField => { string += `${formatFieldObject(jdlFieldObjects[jdlField])}`; }); string = `${string.slice(0, string.length - 1)}`; return string; } function formatFieldObject(jdlFieldObject) { let string = ''; const lines = jdlFieldObject.toString().split('\n'); for (let j = 0; j < lines.length; j++) { string += ` ${lines[j]}\n`; } string = `${string.slice(0, string.length - 1)}\n`; return string; }