Skip to content

Commit

Permalink
Move some checks and asserts where it makes sense (#28382)
Browse files Browse the repository at this point in the history
* move some checks and asserts where it makes sense

* align types

* use pick instead of Omit in base-application types

* adjust some types

* clean type

* moved primary key field processing to bootstrap-app instead of bootstrap-app-base

* moved primary key field processing to bootstrap-app instead of bootstrap-app-base

* duplicate code to avoid breaking API change

* dedupe derived primary key array

* rolledback move of derived primary key actions
  • Loading branch information
Tcharl authored Jan 10, 2025
1 parent 0b26382 commit 8e9aace
Show file tree
Hide file tree
Showing 15 changed files with 49 additions and 35 deletions.
16 changes: 12 additions & 4 deletions generators/base-application/generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,12 @@ import {
import type {
ConfiguringEachEntityTaskParam,
TaskTypes as DefaultTaskTypes,
EntityTaskParam,
EntityToLoad,
LoadingEntitiesTaskParam,
PostWritingEntitiesTaskParam,
PreparingEachEntityFieldTaskParam,
PreparingEachEntityRelationshipTaskParam,
PreparingEachEntityTaskParam,
PreparingTaskParam,
TaskParamWithApplication,
TaskParamWithEntities,
Expand Down Expand Up @@ -482,7 +484,7 @@ export default class BaseApplicationGenerator<
* Get entities to prepare.
* @returns {object[]}
*/
getEntitiesDataToPrepare(): EntityTaskParam[] {
getEntitiesDataToPrepare(): Pick<PreparingEachEntityTaskParam, 'entity' | 'entityName' | 'description'>[] {
return this.sharedData.getEntities().map(({ entityName, ...data }) => ({
description: entityName,
entityName,
Expand All @@ -495,7 +497,10 @@ export default class BaseApplicationGenerator<
* Get entities and fields to prepare.
* @returns {object[]}
*/
getEntitiesFieldsDataToPrepare() {
getEntitiesFieldsDataToPrepare(): Pick<
PreparingEachEntityFieldTaskParam,
'entity' | 'entityName' | 'field' | 'fieldName' | 'description'
>[] {
return this.getEntitiesDataToPrepare()
.map(({ entity, entityName, ...data }) => {
if (!entity.fields) return [];
Expand All @@ -517,7 +522,10 @@ export default class BaseApplicationGenerator<
* Get entities and relationships to prepare.
* @returns {object[]}
*/
getEntitiesRelationshipsDataToPrepare() {
getEntitiesRelationshipsDataToPrepare(): Pick<
PreparingEachEntityRelationshipTaskParam,
'entity' | 'entityName' | 'relationship' | 'relationshipName' | 'description'
>[] {
return this.getEntitiesDataToPrepare()
.map(({ entity, entityName, ...data }) => {
if (!entity.relationships) return [];
Expand Down
2 changes: 1 addition & 1 deletion generators/base-application/support/relationship.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ export const loadEntitiesOtherSide = (entities: Entity[], { application }: { app
relationship.otherEntity = otherEntity;
const otherRelationship = findOtherRelationshipInRelationships(entity.name, relationship, otherEntity.relationships ?? []);
if (otherRelationship) {
relationship.otherRelationship = otherRelationship as Relationship;
relationship.otherRelationship = otherRelationship;
otherRelationship.otherEntityRelationshipName = otherRelationship.otherEntityRelationshipName ?? relationship.relationshipName;
relationship.otherEntityRelationshipName = relationship.otherEntityRelationshipName ?? otherRelationship.relationshipName;
if (
Expand Down
14 changes: 7 additions & 7 deletions generators/base-core/generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -280,7 +280,7 @@ You can ignore this error by passing '--skip-checks' to jhipster command.`);
*
* @param {string} version - A valid semver version string
*/
isJhipsterVersionLessThan(version) {
isJhipsterVersionLessThan(version: string): boolean {
const jhipsterOldVersion = this.sharedData.getControl().jhipsterOldVersion;
return this.isVersionLessThan(jhipsterOldVersion, version);
}
Expand All @@ -289,7 +289,7 @@ You can ignore this error by passing '--skip-checks' to jhipster command.`);
* Wrapper for `semver.lt` to check if the oldVersion exists and is less than the newVersion.
* Can be used by blueprints.
*/
isVersionLessThan(oldVersion: string | null, newVersion: string) {
isVersionLessThan(oldVersion: string | null, newVersion: string): boolean {
return oldVersion ? semverLessThan(oldVersion, newVersion) : false;
}

Expand Down Expand Up @@ -647,7 +647,7 @@ You can ignore this error by passing '--skip-checks' to jhipster command.`);
* Set false to create a changelog date incrementing the last one.
* @return {String} Changelog date.
*/
dateFormatForLiquibase(reproducible?: boolean) {
dateFormatForLiquibase(reproducible?: boolean): string {
const control = this.sharedData.getControl();
reproducible = reproducible ?? Boolean(control.reproducible);
// Use started counter or use stored creationTimestamp if creationTimestamp option is passed
Expand Down Expand Up @@ -693,7 +693,7 @@ You can ignore this error by passing '--skip-checks' to jhipster command.`);
/**
* Alternative templatePath that fetches from the blueprinted generator, instead of the blueprint.
*/
jhipsterTemplatePath(...path: string[]) {
jhipsterTemplatePath(...path: string[]): string {
let existingGenerator: string;
try {
existingGenerator = this._jhipsterGenerator ?? requireNamespace(this.options.namespace).generator;
Expand Down Expand Up @@ -751,7 +751,7 @@ You can ignore this error by passing '--skip-checks' to jhipster command.`);
/**
* Remove File
*/
removeFile(...path: string[]) {
removeFile(...path: string[]): string {
const destinationFile = this.destinationPath(...path);
const relativePath = relative((this.env as any).logCwd, destinationFile);
// Delete from memory fs to keep updated.
Expand All @@ -771,7 +771,7 @@ You can ignore this error by passing '--skip-checks' to jhipster command.`);
* Remove Folder
* @param path
*/
removeFolder(...path: string[]) {
removeFolder(...path: string[]): void {
const destinationFolder = this.destinationPath(...path);
const relativePath = relative((this.env as any).logCwd, destinationFolder);
// Delete from memory fs to keep updated.
Expand All @@ -789,7 +789,7 @@ You can ignore this error by passing '--skip-checks' to jhipster command.`);
/**
* Fetch files from the generator-jhipster instance installed
*/
fetchFromInstalledJHipster(...path: string[]) {
fetchFromInstalledJHipster(...path: string[]): string {
if (path) {
return joinPath(__dirname, '..', ...path);
}
Expand Down
7 changes: 4 additions & 3 deletions generators/base-entity-changes/generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
* limitations under the License.
*/
import { existsSync, readFileSync } from 'fs';
import type { Field } from '../base-application/index.js';
import GeneratorBaseApplication from '../base-application/index.js';
import { PRIORITY_NAMES } from '../base-application/priorities.js';
import { loadEntitiesAnnotations, loadEntitiesOtherSide } from '../base-application/support/index.js';
Expand Down Expand Up @@ -219,11 +220,11 @@ export default abstract class GeneratorBaseEntityChanges extends GeneratorBaseAp
});
}

private hasAnyDefaultValue(field) {
return field.defaultValue !== undefined || field.defaultValueComputed;
private hasAnyDefaultValue(field: Field): boolean {
return field.defaultValue !== undefined || field.defaultValueComputed !== undefined;
}

private doDefaultValuesDiffer(field1, field2) {
private doDefaultValuesDiffer(field1: Field, field2: Field): boolean {
return field1.defaultValue !== field2.defaultValue || field1.defaultValueComputed !== field2.defaultValueComputed;
}
}
2 changes: 1 addition & 1 deletion generators/base-workspaces/generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ export default abstract class BaseWorkspacesGenerator extends BaseGenerator<Work
);
}

getArgsForPriority(priorityName): any {
getArgsForPriority(priorityName: string): any {
const args = super.getArgsForPriority(priorityName);
if (
![
Expand Down
3 changes: 2 additions & 1 deletion generators/bootstrap-application-base/generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ import { loadCommandConfigsIntoApplication, loadCommandConfigsKeysIntoTemplatesC
import { getConfigWithDefaults } from '../../lib/jhipster/default-application-options.js';
import { removeFieldsWithNullishValues } from '../base/support/index.js';
import { convertFieldBlobType, getBlobContentType, isFieldBinaryType, isFieldBlobType } from '../../lib/application/field-types.js';
import type { Entity } from '../../lib/types/application/entity.js';
import { createAuthorityEntity, createUserEntity, createUserManagementEntity } from './utils.js';
import { exportJDLTransform, importJDLTransform } from './support/index.js';

Expand Down Expand Up @@ -443,7 +444,7 @@ export default class BootstrapApplicationBase extends BaseApplicationGenerator {
entity.anyRelationshipIsRequired = entity.relationships.some(rel => rel.relationshipRequired || rel.id);
},
checkForCircularRelationships({ entity }) {
const detectCyclicRequiredRelationship = (entity, relatedEntities) => {
const detectCyclicRequiredRelationship = (entity: Entity, relatedEntities: Set<Entity>) => {
if (relatedEntities.has(entity)) return true;
relatedEntities.add(entity);
return entity.relationships
Expand Down
4 changes: 4 additions & 0 deletions generators/bootstrap-application-client/generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import BaseApplicationGenerator from '../base-application/index.js';
import { loadStoredAppOptions } from '../app/support/index.js';
import clientCommand from '../client/command.js';
import { loadConfig, loadDerivedConfig } from '../../lib/internal/index.js';
import { getFrontendAppName } from '../base/support/index.js';

export default class BootStrapApplicationClient extends BaseApplicationGenerator {
constructor(args: any, options: any, features: any) {
Expand Down Expand Up @@ -68,6 +69,9 @@ export default class BootStrapApplicationClient extends BaseApplicationGenerator
loadDerivedConfig(clientCommand.configs, { application });
loadDerivedClientConfig({ application });
},
prepareForTemplates({ application }) {
application.frontendAppName = getFrontendAppName({ baseName: application.baseName });
},
});
}

Expand Down
4 changes: 0 additions & 4 deletions generators/bootstrap-application-server/generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@ import { getPomVersionProperties } from '../maven/support/index.js';
import { prepareField as prepareFieldForLiquibaseTemplates } from '../liquibase/support/index.js';
import { getDockerfileContainers } from '../docker/utils.js';
import { normalizePathEnd } from '../base/support/path.js';
import { getFrontendAppName } from '../base/support/index.js';
import { getMainClassName } from '../java/support/index.js';
import { loadConfig, loadDerivedConfig } from '../../lib/internal/index.js';
import serverCommand from '../server/command.js';
Expand Down Expand Up @@ -126,11 +125,8 @@ export default class BoostrapApplicationServer extends BaseApplicationGenerator
prepareForTemplates({ application: app }) {
const application: any = app;
// Application name modified, using each technology's conventions
application.frontendAppName = getFrontendAppName({ baseName: application.baseName });
application.mainClass = getMainClassName({ baseName: application.baseName });

application.jhiTablePrefix = hibernateSnakeCase(application.jhiPrefix);

application.mainJavaDir = SERVER_MAIN_SRC_DIR;
application.mainJavaPackageDir = normalizePathEnd(`${SERVER_MAIN_SRC_DIR}${application.packageFolder}`);
application.mainJavaResourceDir = SERVER_MAIN_RES_DIR;
Expand Down
3 changes: 2 additions & 1 deletion generators/bootstrap-application/generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import {
import { preparePostEntityServerDerivedProperties } from '../server/support/index.js';
import { loadStoredAppOptions } from '../app/support/index.js';
import { JHIPSTER_DOCUMENTATION_ARCHIVE_PATH, JHIPSTER_DOCUMENTATION_URL } from '../generator-constants.js';
import type { Field } from '../../lib/types/base/field.js';

const {
Validations: { MAX, MIN, MAXLENGTH, MINLENGTH, MAXBYTES, MINBYTES, PATTERN },
Expand Down Expand Up @@ -102,7 +103,7 @@ export default class BootstrapApplicationGenerator extends BaseApplicationGenera
entityConfig.name = entityName;
}

entityConfig.fields!.forEach((field: any) => {
entityConfig.fields!.forEach((field: Field) => {
const { fieldName, fieldType, fieldValidateRules } = field;

assert(fieldName, `fieldName is missing in .jhipster/${entityName}.json for field ${stringifyApplicationData(field)}`);
Expand Down
1 change: 1 addition & 0 deletions generators/client/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ export type FrontendApplication = ApplicationClientProperties &
clientWebappDir?: string;
webappEnumerationsDir?: string;
clientFrameworkBuiltIn?: boolean;
frontendAppName?: string;
};

/**
Expand Down
3 changes: 2 additions & 1 deletion generators/server/support/prepare-relationship.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import type { Relationship } from '../../../lib/types/application/relationship.js';
import { mutateData } from '../../../lib/utils/object.js';
import { formatDocAsApiDescription, formatDocAsJavaDoc } from '../../java/support/doc.js';
import type { Entity } from '../../../lib/types/application/index.js';

export function prepareRelationship({ relationship }: { relationship: Relationship; entity: any }) {
export function prepareRelationship({ relationship }: { relationship: Relationship; entity: Entity }) {
if (relationship.documentation) {
mutateData(relationship, {
__override__: false,
Expand Down
4 changes: 2 additions & 2 deletions lib/types/application/entity.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,8 @@ export interface Entity<F extends BaseField = Field, R extends BaseRelationship
changelogDateForRecent: any;
/** @experimental */
auditableEntity?: boolean;
relationships: (IsNever<R> extends true ? Relationship<Omit<Entity, 'relationships'>> : R)[];
otherRelationships: (IsNever<R> extends true ? Relationship<Omit<Entity, 'relationships'>> : R)[];
relationships: (IsNever<R> extends true ? Relationship : R)[];
otherRelationships: (IsNever<R> extends true ? Relationship : R)[];

primaryKey?: PrimaryKey<F>;

Expand Down
7 changes: 0 additions & 7 deletions lib/types/application/field.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,6 @@ export interface Field extends Property, BaseField {
// Validation
fieldValidate?: boolean;
unique?: boolean;
fieldValidateRules?: string[];
fieldValidateRulesPattern?: string | RegExp;
fieldValidateRulesMaxlength?: number;
fieldValidateRulesMax?: number;
fieldValidateRulesMin?: number;
fieldValidateRulesMinlength?: number;
fieldValidationRequired?: boolean;
maxlength?: number;

// Temporary fields for Faker
Expand Down
5 changes: 3 additions & 2 deletions lib/types/application/relationship.d.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
import type { Entity } from '../base/entity.js';
import type { Entity as BaseEntity } from '../base/entity.js';
import type { Relationship as BaseRelationship } from '../base/relationship.js';
import type { DerivedPropertiesOnlyOf } from '../utils/derived-properties.js';
import type { Entity } from './entity.js';
import type { Property } from './property.js';

type RelationshipProperties = DerivedPropertiesOnlyOf<
'relationship',
'LeftSide' | 'RightSide' | 'ManyToOne' | 'OneToMany' | 'OneToOne' | 'ManyToMany'
>;

export interface Relationship<E extends Entity = Entity> extends BaseRelationship, Property, RelationshipProperties {
export interface Relationship<E extends BaseEntity = Entity> extends BaseRelationship, Property, RelationshipProperties {
propertyName: string;
relationshipNameCapitalized: string;

Expand Down
9 changes: 8 additions & 1 deletion lib/types/base/field.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,14 @@ export type Field = Partial<FieldEnum> &
fieldType: FieldType | string;
options?: Record<string, boolean | string | number>;
fieldValidateRules?: string[];

fieldValidateRulesPattern?: string | RegExp;
fieldValidateRulesMaxlength?: number;
fieldValidateRulesMax?: number;
fieldValidateRulesMin?: number;
fieldValidateRulesMinlength?: number;
fieldValidationRequired?: boolean;
fieldValidateRulesMaxbytes?: number;
fieldValidateRulesMinbytes?: number;
/** @deprecated */
fieldTypeJavadoc?: string;
};

0 comments on commit 8e9aace

Please sign in to comment.