Skip to content

Commit

Permalink
cleanup entity generator
Browse files Browse the repository at this point in the history
  • Loading branch information
mshima committed Oct 10, 2023
1 parent e166eae commit 4477fce
Show file tree
Hide file tree
Showing 3 changed files with 86 additions and 111 deletions.
149 changes: 66 additions & 83 deletions generators/entity/generator.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -25,27 +25,17 @@ import * as _ from 'lodash-es';
import BaseApplicationGenerator from '../base-application/index.mjs';
import prompts from './prompts.mjs';
import { JHIPSTER_CONFIG_DIR } from '../generator-constants.mjs';
import { applicationTypes, clientFrameworkTypes, getConfigWithDefaults, reservedKeywords } from '../../jdl/jhipster/index.mjs';
import { GENERATOR_ENTITIES, GENERATOR_ENTITY } from '../generator-list.mjs';
import { removeFieldsWithNullishValues } from '../base/support/index.mjs';
import {
getDBTypeFromDBValue,
hibernateSnakeCase,
loadDerivedPlatformConfig,
loadDerivedServerConfig,
loadServerConfig,
} from '../server/support/index.mjs';
import { loadAppConfig, loadDerivedAppConfig } from '../app/support/index.mjs';
import { loadClientConfig, loadDerivedClientConfig } from '../client/support/index.mjs';
import { loadLanguagesConfig } from '../languages/support/index.mjs';
import { applicationTypes, reservedKeywords } from '../../jdl/jhipster/index.mjs';
import { GENERATOR_BOOTSTRAP_APPLICATION, GENERATOR_ENTITIES, GENERATOR_ENTITY } from '../generator-list.mjs';
import { getDBTypeFromDBValue, hibernateSnakeCase } from '../server/support/index.mjs';
import command from './command.mjs';

const { GATEWAY, MICROSERVICE } = applicationTypes;
const { NO: CLIENT_FRAMEWORK_NO } = clientFrameworkTypes;
const { isReservedClassName } = reservedKeywords;

export default class EntityGenerator extends BaseApplicationGenerator {
name;
application = {};

constructor(args, options, features) {
super(args, options, { unique: 'argument', ...features });
Expand All @@ -55,11 +45,15 @@ export default class EntityGenerator extends BaseApplicationGenerator {
if (!this.fromBlueprint) {
await this.composeWithBlueprints(GENERATOR_ENTITY);
}

if (!this.delegateToBlueprint) {
await this.dependsOnJHipster(GENERATOR_BOOTSTRAP_APPLICATION);
}
}

// Public API method used by the getter and also by Blueprints
get initializing() {
return {
return this.asInitializingTaskGroup({
parseOptions() {
this.parseJHipsterArguments(command.arguments);
const name = _.upperFirst(this.name).replace('.json', '');
Expand All @@ -71,58 +65,71 @@ export default class EntityGenerator extends BaseApplicationGenerator {
const entityExisted = fs.existsSync(this.destinationPath(filename));

this.jhipsterConfig.entities = [...(this.jhipsterConfig.entities ?? []), name];
this.context = {
this.entityData = {
name,
filename,
configExisted,
entityExisted,
configurationFileExists: this.fs.exists(this.destinationPath(filename)),
};

this._setupEntityOptions(this, this, this.context);
this._setupEntityOptions(this, this, this.entityData);
},
/* Use need microservice path to load the entity file */
askForMicroserviceJson: prompts.askForMicroserviceJson,

loadSharedConfig() {
this.application = {};
loadAppConfig({
config: this.jhipsterConfigWithDefaults,
application: this.application,
useVersionPlaceholders: this.useVersionPlaceholders,
});
loadClientConfig({ config: this.jhipsterConfigWithDefaults, application: this.application });
loadLanguagesConfig({ application: this.application, config: this.jhipsterConfigWithDefaults });
// Try to load server config from microservice side, falling back to the app config.
loadServerConfig({
config: getConfigWithDefaults({
...removeFieldsWithNullishValues(this.jhipsterConfig),
...removeFieldsWithNullishValues(this.microserviceConfig ?? {}),
}),
application: this.application,
});
loadOptions() {
if (this.options.db) {
this.entityConfig.databaseType = getDBTypeFromDBValue(this.options.db);
if (this.entityConfig.databaseType === 'sql') {
this.entityConfig.prodDatabaseType = this.options.db;
this.entityConfig.devDatabaseType = this.options.db;
}
}

loadDerivedAppConfig({ application: this.application });
loadDerivedClientConfig({ application: this.application });
loadDerivedServerConfig({ application: this.application });
loadDerivedPlatformConfig({ application: this.application });
if (this.options.skipServer !== undefined) {
this.entityConfig.skipServer = this.options.skipServer;
}
if (this.options.skipDbChangelog !== undefined) {
this.entityConfig.skipDbChangelog = this.options.skipDbChangelog;
}
if (this.options.skipClient !== undefined) {
this.entityConfig.skipClient = this.options.skipClient;
}
},
});
}

get [BaseApplicationGenerator.INITIALIZING]() {
return this.delegateTasksToBlueprint(() => this.initializing);
}

get prompting() {
return this.asPromptingTaskGroup({
/* Use need microservice path to load the entity file */
askForMicroserviceJson: prompts.askForMicroserviceJson,
});
}

get [BaseApplicationGenerator.PROMPTING]() {
return this.delegateTasksToBlueprint(() => this.prompting);
}

get loading() {
return this.asLoadingTaskGroup({
isBuiltInEntity() {
if (this.isBuiltInUser(this.context.name) || this.isBuiltInAuthority(this.context.name)) {
throw new Error(`Is not possible to override built in ${this.context.name}`);
if (this.isBuiltInUser(this.entityData.name) || this.isBuiltInAuthority(this.entityData.name)) {
throw new Error(`Is not possible to override built in ${this.entityData.name}`);
}
},

setupMicroServiceEntity() {
const context = this.context;
setupMicroServiceEntity({ application }) {
const context = this.entityData;

if (this.application.applicationType === MICROSERVICE) {
if (application.applicationType === MICROSERVICE) {
context.microserviceName = this.entityConfig.microserviceName = this.jhipsterConfig.baseName;
if (!this.entityConfig.clientRootFolder) {
context.clientRootFolder = this.entityConfig.clientRootFolder = this.entityConfig.microserviceName;
}
} else if (this.application.applicationType === GATEWAY) {
} else if (application.applicationType === GATEWAY) {
// If microservicePath is set we are loading the entity from the microservice side.
context.useMicroserviceJson = !!this.entityConfig.microservicePath;
if (context.useMicroserviceJson) {
Expand All @@ -147,48 +154,25 @@ export default class EntityGenerator extends BaseApplicationGenerator {
? ''
: this.entityConfig.microserviceName;
}

if (this.jhipsterConfig.applications && !this.entityConfig.skipClient) {
const remoteConfig = this.jhipsterConfig.applications[this.entityConfig.microserviceName];
if (remoteConfig && remoteConfig.clientFramework && remoteConfig.clientFramework !== CLIENT_FRAMEWORK_NO) {
// Gateway requires entities to discover a microfrontend.
// Microfrontends is generated at the microservice side, so skip it at gateway side.
this.entityConfig.skipClient = true;
}
}
}
},

loadOptions() {
const context = this.context;

if (this.options.db) {
context.databaseType = getDBTypeFromDBValue(this.options.db);
context.prodDatabaseType = this.options.db;
context.devDatabaseType = this.options.db;
}

context.skipServer = context.skipServer || this.options.skipServer;
context.skipDbChangelog = context.skipDbChangelog || this.options.skipDbChangelog;
context.skipClient = context.skipClient || this.options.skipClient;
},

loadEntitySpecificOptions() {
this.context.skipClient = this.context.skipClient || this.entityConfig.skipClient;
this.context.databaseType = this.context.databaseType || this.entityConfig.databaseType || this.jhipsterConfig.databaseType;
loadEntitySpecificOptions({ application }) {
this.entityData.skipClient = this.entityData.skipClient || this.entityConfig.skipClient;
this.entityData.databaseType = this.entityData.databaseType || this.entityConfig.databaseType || application.databaseType;
},

validateEntityName() {
const validation = this._validateEntityName(this.context.name);
const validation = this._validateEntityName(this.entityData.name);
if (validation !== true) {
throw new Error(validation);
}
},

bootstrapConfig() {
const context = this.context;
bootstrapConfig({ application }) {
const context = this.entityData;
const entityName = context.name;
if ([MICROSERVICE, GATEWAY].includes(this.application.applicationType)) {
if ([MICROSERVICE, GATEWAY].includes(application.applicationType)) {
if (this.entityConfig.databaseType === undefined) {
this.entityConfig.databaseType = context.databaseType;
}
Expand All @@ -205,14 +189,13 @@ export default class EntityGenerator extends BaseApplicationGenerator {
this.log.verboseInfo(`\nThe entity ${entityName} is being created.\n`);
}
},
};
});
}

get [BaseApplicationGenerator.INITIALIZING]() {
return this.delegateTasksToBlueprint(() => this.initializing);
get [BaseApplicationGenerator.LOADING]() {
return this.delegateTasksToBlueprint(() => this.loading);
}

// Public API method used by the getter and also by Blueprints
get postPreparing() {
return this.asPostPreparingTaskGroup({
/* ask question to user if s/he wants to update entity */
Expand All @@ -239,7 +222,7 @@ export default class EntityGenerator extends BaseApplicationGenerator {
async composeEntities() {
// We need to compose with others entities to update relationships.
await this.composeWithJHipster(GENERATOR_ENTITIES, {
generatorArgs: this.options.singleEntity ? [this.context.name] : [],
generatorArgs: this.options.singleEntity ? [this.entityData.name] : [],
generatorOptions: {
skipDbChangelog: this.options.skipDbChangelog,
skipInstall: this.options.skipInstall,
Expand All @@ -257,7 +240,7 @@ export default class EntityGenerator extends BaseApplicationGenerator {
get end() {
return {
end() {
this.log.log(chalk.bold.green(`Entity ${this.context.entityNameCapitalized} generated successfully.`));
this.log.log(chalk.bold.green(`Entity ${this.entityData.entityNameCapitalized} generated successfully.`));
},
};
}
Expand Down Expand Up @@ -325,7 +308,7 @@ export default class EntityGenerator extends BaseApplicationGenerator {
if (entityName.indexOf('Detail', entityName.length - 'Detail'.length) !== -1) {
return "The entity name cannot end with 'Detail'";
}
if (!this.context.skipServer && isReservedClassName(entityName)) {
if (!this.entityData.skipServer && isReservedClassName(entityName)) {
return 'The entity name cannot contain a Java or JHipster reserved keyword';
}
return true;
Expand Down
28 changes: 14 additions & 14 deletions generators/entity/prompts.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ const getFieldNameUndercored = fields =>
);

function askForMicroserviceJson() {
const context = this.context;
const context = this.entityData;
if (this.jhipsterConfig.applicationType !== GATEWAY || context.configExisted) {
return undefined;
}
Expand Down Expand Up @@ -120,7 +120,7 @@ function askForMicroserviceJson() {
}

function askForUpdate() {
const context = this.context;
const context = this.entityData;
// ask only if running an existing entity without arg option --force or --regenerate
const isForce = this.options.force || context.regenerate;
context.updateEntity = 'regenerate'; // default if skipping questions by --force
Expand Down Expand Up @@ -163,7 +163,7 @@ function askForUpdate() {
}

function askForFields() {
const context = this.context;
const context = this.entityData;
// don't prompt if data is imported from a file
if (this.options.defaults || (context.useConfigurationFile && context.updateEntity !== 'add')) {
return undefined;
Expand All @@ -177,7 +177,7 @@ function askForFields() {
}

function askForFieldsToRemove() {
const context = this.context;
const context = this.entityData;
// prompt only if data is imported from a file
if (!context.useConfigurationFile || context.updateEntity !== 'remove' || this.entityConfig.fields.length === 0) {
return undefined;
Expand Down Expand Up @@ -217,7 +217,7 @@ function askForFieldsToRemove() {
}

function askForRelationships() {
const context = this.context;
const context = this.entityData;
if (this.options.defaults) {
return undefined;
}
Expand All @@ -233,7 +233,7 @@ function askForRelationships() {
}

function askForRelationsToRemove() {
const context = this.context;
const context = this.entityData;
// prompt only if data is imported from a file
if (!context.useConfigurationFile || context.updateEntity !== 'remove' || this.entityConfig.relationships.length === 0) {
return undefined;
Expand Down Expand Up @@ -279,7 +279,7 @@ function askForRelationsToRemove() {
}

function askForFiltering() {
const context = this.context;
const context = this.entityData;
// don't prompt if server is skipped, or the backend is not sql, or no service requested
if (context.useConfigurationFile || context.skipServer || context.databaseType !== 'sql' || this.entityConfig.service === 'no') {
return undefined;
Expand Down Expand Up @@ -308,7 +308,7 @@ function askForFiltering() {
}

function askForReadOnly() {
const context = this.context;
const context = this.entityData;
// don't prompt if data is imported from a file
if (context.useConfigurationFile) {
return undefined;
Expand All @@ -327,7 +327,7 @@ function askForReadOnly() {
}

function askForDTO() {
const context = this.context;
const context = this.entityData;
// don't prompt if data is imported from a file or server is skipped or if no service layer
if (context.useConfigurationFile || context.skipServer || this.entityConfig.service === 'no') {
return undefined;
Expand Down Expand Up @@ -356,7 +356,7 @@ function askForDTO() {
}

function askForService() {
const context = this.context;
const context = this.entityData;
// don't prompt if data is imported from a file or server is skipped
if (context.useConfigurationFile || context.skipServer) {
return undefined;
Expand Down Expand Up @@ -389,7 +389,7 @@ function askForService() {
}

function askForPagination() {
const context = this.context;
const context = this.entityData;
// don't prompt if data are imported from a file
if (context.useConfigurationFile) {
return undefined;
Expand Down Expand Up @@ -429,7 +429,7 @@ function askForPagination() {
* ask question for a field creation
*/
function askForField() {
const context = this.context;
const context = this.entityData;
this.log.log(chalk.green(`\nGenerating field #${this.entityConfig.fields.length + 1}\n`));
const skipServer = context.skipServer;
const databaseType = context.databaseType;
Expand Down Expand Up @@ -879,7 +879,7 @@ function askForField() {
* ask question for a relationship creation
*/
function askForRelationship() {
const context = this.context;
const context = this.entityData;
const name = context.name;
this.log.log(chalk.green('\nGenerating relationships to other entities\n'));
const prompts = [
Expand Down Expand Up @@ -1072,7 +1072,7 @@ function askForRelationship() {
* Show the entity and it's fields and relationships in console
*/
function logFieldsAndRelationships() {
const context = this.context;
const context = this.entityData;
if (this.entityConfig.fields.length > 0 || this.entityConfig.relationships.length > 0) {
this.log.log(chalk.red(chalk.white('\n================= ') + context.name + chalk.white(' =================')));
}
Expand Down
Loading

0 comments on commit 4477fce

Please sign in to comment.