Skip to content

Commit

Permalink
internal: add type to mutateData (#27932)
Browse files Browse the repository at this point in the history
  • Loading branch information
mshima authored Nov 19, 2024
1 parent 123edc8 commit 5135b2f
Show file tree
Hide file tree
Showing 37 changed files with 185 additions and 122 deletions.
2 changes: 1 addition & 1 deletion generators/angular/cleanup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ export default asWritingTask(function cleanupOldFilesTask(this, { application })
this.removeFile(`${application.clientSrcDir}app/shared/login/login.component.ts`);
this.removeFile(`${application.clientSrcDir}app/shared/login/login.component.html`);
this.removeFile(`${application.clientSrcDir}app/core/auth/user-route-access-service.ts`);
if (!application.authenticationTypeSession || !(application as any).communicationSpringWebsocket) {
if (!application.authenticationTypeSession || !application.communicationSpringWebsocket) {
this.removeFile(`${application.clientSrcDir}app/core/auth/csrf.service.ts`);
}
this.removeFolder(`${application.clientSrcDir}app/core/login`);
Expand Down
2 changes: 1 addition & 1 deletion generators/angular/generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ export default class AngularGenerator extends BaseApplicationGenerator {

return returnValue;
},
});
} as any);
},
});
}
Expand Down
5 changes: 3 additions & 2 deletions generators/app/support/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import detectLanguage from '../../languages/support/detect-language.js';
import { loadConfig, loadDerivedConfig } from '../../../lib/internal/index.js';
import serverCommand from '../../server/command.js';
import { packageJson } from '../../../lib/index.js';
import type { ApplicationType } from '../../../lib/types/application/application.js';

const { GATLING, CUCUMBER, CYPRESS } = testFrameworkTypes;
const { GATEWAY, MONOLITH } = applicationTypes;
Expand Down Expand Up @@ -77,7 +78,7 @@ export const loadAppConfig = ({
useVersionPlaceholders,
}: {
config: any;
application: any;
application: ApplicationType;
useVersionPlaceholders?: boolean;
}) => {
loadConfig(serverCommand.configs, { config, application });
Expand Down Expand Up @@ -152,7 +153,7 @@ export const loadDerivedAppConfig = ({ application }: { application: any }) => {

projectDescription: ({ projectDescription, baseName }) => projectDescription ?? `Description for ${baseName}`,
endpointPrefix: ({ applicationType, lowercaseBaseName }) => (applicationType === 'microservice' ? `services/${lowercaseBaseName}` : ''),
});
} as any);

if (application.microfrontends && application.microfrontends.length > 0) {
application.microfrontends.forEach(microfrontend => {
Expand Down
16 changes: 8 additions & 8 deletions generators/base-application/generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -580,7 +580,7 @@ export default class BaseApplicationGenerator<
});
});
},
} as any);
});

this.queueTask({
queueName: LOADING_ENTITIES_QUEUE,
Expand All @@ -599,7 +599,7 @@ export default class BaseApplicationGenerator<
});
});
},
} as any);
});

this.queueTask({
queueName: PREPARING_EACH_ENTITY_QUEUE,
Expand All @@ -620,7 +620,7 @@ export default class BaseApplicationGenerator<
});
});
},
} as any);
});

this.queueTask({
queueName: PREPARING_EACH_ENTITY_FIELD_QUEUE,
Expand All @@ -640,7 +640,7 @@ export default class BaseApplicationGenerator<
});
});
},
} as any);
});

this.queueTask({
queueName: PREPARING_EACH_ENTITY_RELATIONSHIP_QUEUE,
Expand All @@ -660,7 +660,7 @@ export default class BaseApplicationGenerator<
});
});
},
} as any);
});

this.queueTask({
queueName: POST_PREPARING_EACH_ENTITY_QUEUE,
Expand All @@ -680,7 +680,7 @@ export default class BaseApplicationGenerator<
});
});
},
} as any);
});

this.queueTask({
queueName: WRITING_ENTITIES_QUEUE,
Expand All @@ -697,7 +697,7 @@ export default class BaseApplicationGenerator<
});
});
},
} as any);
});

this.queueTask({
queueName: POST_WRITING_ENTITIES_QUEUE,
Expand All @@ -714,6 +714,6 @@ export default class BaseApplicationGenerator<
});
});
},
} as any);
});
}
}
89 changes: 47 additions & 42 deletions generators/base-application/support/prepare-entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,11 @@ import { binaryOptions } from '../../../lib/jdl/core/built-in-options/index.js';

import type { Entity } from '../../../lib/types/application/index.js';
import type CoreGenerator from '../../base-core/generator.js';
import { fieldIsEnum } from './field-utils.js';
import type { PrimaryKey } from '../../../lib/types/application/entity.js';
import type { ApplicationConfiguration } from '../../../lib/types/application/yo-rc.js';
import type { ApplicationType } from '../../../lib/types/application/application.js';
import { fieldToReference } from './prepare-field.js';
import { fieldIsEnum } from './field-utils.js';

const NO_SEARCH_ENGINE = searchEngineTypes.NO;
const { MapperTypes } = entityOptions;
Expand Down Expand Up @@ -135,7 +138,9 @@ export const entityDefaultConfig = {
},
};

export default function prepareEntity(entityWithConfig, generator, application) {
export default function prepareEntity(entityWithConfig: Entity, generator, application: ApplicationType) {
const { applicationTypeMicroservice, microfrontend } = application;

const entityName = upperFirst(entityWithConfig.name);
const entitySuffix = entityWithConfig.entitySuffix ?? application.entitySuffix;
mutateData(entityWithConfig, entityDefaultConfig, BASE_TEMPLATE_DATA);
Expand Down Expand Up @@ -172,23 +177,26 @@ export default function prepareEntity(entityWithConfig, generator, application)
entityAuthority: entityWithConfig.adminEntity ? 'ROLE_ADMIN' : undefined,
});

const dto = entityWithConfig.dto && entityWithConfig.dto !== NO_DTO;
if (dto) {
mutateData(entityWithConfig, {
dtoClass: `${entityWithConfig.entityClass}${application.dtoSuffix ?? ''}`,
dtoInstance: `${entityWithConfig.entityInstance}${application.dtoSuffix ?? ''}`,
});
}

mutateData(entityWithConfig, {
persistClass: `${entityWithConfig.entityClass}${entitySuffix ?? ''}`,
persistInstance: `${entityWithConfig.entityInstance}${entitySuffix ?? ''}`,
});

mutateData(entityWithConfig, {
restClass: dto ? entityWithConfig.dtoClass : entityWithConfig.persistClass,
restInstance: dto ? entityWithConfig.dtoInstance : entityWithConfig.persistInstance,
});
const dto = entityWithConfig.dto && entityWithConfig.dto !== NO_DTO;
if (dto) {
const { dtoSuffix = '' } = application;
mutateData(entityWithConfig, {
dtoClass: `${entityWithConfig.entityClass}${dtoSuffix}`,
dtoInstance: `${entityWithConfig.entityInstance}${dtoSuffix}`,
restClass: ({ dtoClass }) => dtoClass!,
restInstance: ({ dtoInstance }) => dtoInstance!,
});
} else {
mutateData(entityWithConfig, {
restClass: ({ persistClass }) => persistClass!,
restInstance: ({ persistInstance }) => persistInstance!,
});
}

mutateData(entityWithConfig, {
entityNamePluralizedAndSpinalCased: kebabCase(entityWithConfig.entityNamePlural),
Expand All @@ -206,7 +214,7 @@ export default function prepareEntity(entityWithConfig, generator, application)
mutateData(entityWithConfig, {
__override__: false,
entityFileName: data => kebabCase(data.entityNameCapitalized + upperFirst(data.entityAngularJSSuffix)),
entityAngularName: data => data.entityClass + upperFirstCamelCase(entityWithConfig.entityAngularJSSuffix),
entityAngularName: data => data.entityClass + upperFirstCamelCase(entityWithConfig.entityAngularJSSuffix!),
entityAngularNamePlural: data => pluralize(data.entityAngularName),
entityApiUrl: data => data.entityNamePluralizedAndSpinalCased,
});
Expand Down Expand Up @@ -234,35 +242,31 @@ export default function prepareEntity(entityWithConfig, generator, application)

mutateData(entityWithConfig, {
__override__: false,
i18nKeyPrefix: data => data.i18nKeyPrefix ?? `${data.frontendAppName}.${data.entityTranslationKey}`,
i18nKeyPrefix: data => data.i18nKeyPrefix ?? `${application.frontendAppName}.${data.entityTranslationKey}`,
i18nAlertHeaderPrefix: data =>
(data.i18nAlertHeaderPrefix ?? data.microserviceAppName)
? `${data.microserviceAppName}.${data.entityTranslationKey}`
: data.i18nKeyPrefix,
hasRelationshipWithBuiltInUser: ({ relationships }) => relationships.some(relationship => relationship.otherEntity.builtInUser),
saveUserSnapshot: ({ hasRelationshipWithBuiltInUser, dto }) =>
application.applicationTypeMicroservice &&
application.authenticationTypeOauth2 &&
hasRelationshipWithBuiltInUser &&
dto === NO_MAPPER,
applicationTypeMicroservice && application.authenticationTypeOauth2 && hasRelationshipWithBuiltInUser && dto === NO_MAPPER,
entityApi: ({ microserviceName }) => (microserviceName ? `services/${microserviceName.toLowerCase()}/` : ''),
entityPage: ({ microserviceName, entityFileName }) =>
microserviceName && microfrontend && applicationTypeMicroservice
? `${microserviceName.toLowerCase()}/${entityFileName}`
: `${entityFileName}`,
});

const { microserviceName, entityFileName, microfrontend } = entityWithConfig;
entityWithConfig.entityApi = microserviceName ? `services/${microserviceName.toLowerCase()}/` : '';
entityWithConfig.entityPage =
entityWithConfig.entityPage ??
(microfrontend && microserviceName && entityWithConfig.applicationType === MICROSERVICE
? `${microserviceName.toLowerCase()}/${entityFileName}`
: `${entityFileName}`);

entityWithConfig.generateFakeData = type => {
const fieldsToGenerate =
type === 'cypress' ? entityWithConfig.fields.filter(field => !field.id || !field.autoGenerate) : entityWithConfig.fields;
const fieldEntries = fieldsToGenerate.map(field => {
const fieldData = field.generateFakeData(type);
if (!field.nullable && fieldData === null) return undefined;
return [field.fieldName, fieldData];
});
const fieldEntries: [string, any][] = fieldsToGenerate
.map(field => {
const fieldData = field.generateFakeData!(type);
if (!field.nullable && fieldData === null) return undefined;
return [field.fieldName, fieldData];
})
.filter(Boolean) as any;
const withError = fieldEntries.find(entry => !entry);
if (withError) {
generator.log.warn(`Error generating a full sample for entity ${entityName}`);
Expand All @@ -275,7 +279,7 @@ export default function prepareEntity(entityWithConfig, generator, application)
return entityWithConfig;
}

export function derivedPrimaryKeyProperties(primaryKey) {
export function derivedPrimaryKeyProperties(primaryKey: PrimaryKey) {
mutateData(primaryKey, {
hasUUID: primaryKey.fields?.some(field => field.fieldType === UUID),
hasLong: primaryKey.fields?.some(field => field.fieldType === LONG),
Expand All @@ -285,7 +289,7 @@ export function derivedPrimaryKeyProperties(primaryKey) {
typeLong: primaryKey.type === LONG,
typeInteger: primaryKey.type === INTEGER,
typeNumeric: !primaryKey.composite && primaryKey.fields[0].fieldTypeNumeric,
});
} as any);
}

export function prepareEntityPrimaryKeyForTemplates(
Expand Down Expand Up @@ -497,12 +501,15 @@ function fieldToId(field) {
* @param {Object} config - config object.
* @returns {Object} the entity parameter for chaining.
*/
export function loadRequiredConfigIntoEntity(this: BaseGenerator | void, entity, config) {
export function loadRequiredConfigIntoEntity<E extends Partial<Entity>>(
this: BaseGenerator | void,
entity: E,
config: ApplicationConfiguration,
): E {
mutateData(entity, {
__override__: false,
applicationType: config.applicationType,
baseName: config.baseName,
frontendAppName: config.frontendAppName,
authenticationType: config.authenticationType,
reactive: config.reactive,
microfrontend: config.microfrontend,
Expand All @@ -512,17 +519,15 @@ export function loadRequiredConfigIntoEntity(this: BaseGenerator | void, entity,
databaseType: config.databaseType,
prodDatabaseType: config.prodDatabaseType,

skipUiGrouping: config.skipUiGrouping,
searchEngine: config.searchEngine,

jhiPrefix: config.jhiPrefix,
entitySuffix: config.entitySuffix,
dtoSuffix: config.dtoSuffix,
packageName: config.packageName,
packageFolder: config.packageFolder,
microserviceName: ({ builtIn }) => (!builtIn && config.applicationType === MICROSERVICE ? config.baseName : undefined),
});
if (entity.searchEngine === true && (!entity.microserviceName || entity.microserviceName === config.baseName)) {
} as any);
if ((entity as any).searchEngine === true && (!entity.microserviceName || entity.microserviceName === config.baseName)) {
// If the entity belongs to this application and searchEngine is true.
if (config.searchEngine && config.searchEngine !== NO_SEARCH_ENGINE) {
// Replace with the searchEngine from the application.
Expand Down Expand Up @@ -647,7 +652,7 @@ function preparePostEntityCommonDerivedPropertiesNotTyped(entity: any) {
entity.eagerLoad ||
// Fetch relationships if otherEntityField differs otherwise the id is enough
(ownerSide && otherEntity.primaryKey.name !== otherEntityField)),
});
} as any);
});
entity.relationshipsContainEagerLoad = entity.relationships.some(relationship => relationship.relationshipEagerLoad);
entity.containsBagRelationships = entity.relationships.some(relationship => relationship.bagRelationship);
Expand Down
4 changes: 2 additions & 2 deletions generators/base-application/support/prepare-field.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,9 @@ describe('generator - base-application - support - prepareField', () => {
Object.setPrototypeOf(defaultGenerator, BaseGenerator.prototype);

const defaultEntity = prepareEntityForTemplates(
loadRequiredConfigIntoEntity({ changelogDate: formatDateForChangelog(new Date()), name: 'Entity' }, defaultConfig),
loadRequiredConfigIntoEntity({ changelogDate: formatDateForChangelog(new Date()), name: 'Entity' } as any, defaultConfig as any),
defaultGenerator,
defaultConfig,
defaultConfig as any,
);

describe('prepareFieldForTemplates', () => {
Expand Down
2 changes: 1 addition & 1 deletion generators/base-application/support/prepare-field.ts
Original file line number Diff line number Diff line change
Expand Up @@ -296,7 +296,7 @@ function prepareCommonFieldForTemplates(entityWithConfig: Entity, field: Field,
fieldNameHumanized: ({ fieldName }) => startCase(fieldName),
fieldTranslationKey: ({ fieldName }) => `${entityWithConfig.i18nKeyPrefix}.${fieldName}`,
tsType: ({ fieldType }) => getTypescriptType(fieldType),
});
} as any);

prepareProperty(field);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ export default function prepareRelationship(
// let ownerSide true when type is 'many-to-one' for convenience.
// means that this side should control the reference.
ownerSide: relationship.otherEntity.embedded || relationshipManyToOne || (relationshipLeftSide && !relationshipOneToMany),
persistableRelationship: ({ ownerSide }) => ownerSide,
persistableRelationship: ({ ownerSide }) => ownerSide!,
relationshipUpdateBackReference: ({ ownerSide, relationshipRightSide, otherEntity }) =>
!otherEntity.embedded && (entityWithConfig.databaseType === NEO4J ? relationshipRightSide : !ownerSide),

Expand Down
3 changes: 3 additions & 0 deletions generators/base-application/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@ export type BaseApplication = {
skipServer?: boolean;
monorepository?: boolean;

blueprints?: { name: string; version: string }[];
testFrameworks?: string[];

/** Customize templates sourceFile and destinationFile */
customizeTemplatePaths: ((
this: CoreGenerator,
Expand Down
8 changes: 4 additions & 4 deletions generators/bootstrap-application-server/generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,10 +148,10 @@ export default class BoostrapApplicationServer extends BaseApplicationGenerator

get loadingEntities() {
return this.asLoadingEntitiesTaskGroup({
loadingEntities({ application, entitiesToLoad }) {
loadingEntities({ entitiesToLoad }) {
for (const { entityName } of entitiesToLoad) {
const entity = this.sharedData.getEntity(entityName);
loadRequiredConfigIntoEntity.call(this, entity, application);
loadRequiredConfigIntoEntity.call(this, entity, this.jhipsterConfigWithDefaults);
}
},
requiredOtherSideRelationships() {
Expand All @@ -166,8 +166,8 @@ export default class BoostrapApplicationServer extends BaseApplicationGenerator

get preparingEachEntity() {
return this.asPreparingEachEntityTaskGroup({
prepareEntity({ entity }) {
prepareEntityServerForTemplates(entity);
prepareEntity({ entity, application }) {
prepareEntityServerForTemplates(entity, application);
loadRequiredConfigDerivedProperties(entity);
},
preparePrimaryKey({ entity, application }) {
Expand Down
Loading

0 comments on commit 5135b2f

Please sign in to comment.