Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

More type checking #26269

Merged
merged 5 commits into from
May 26, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions jdl/converters/json-to-jdl-converter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import { readJSONFile } from '../readers/json-file-reader.js';
import { convertApplicationToJDL } from './json-to-jdl-application-converter.js';
import { convertEntitiesToJDL } from './json-to-jdl-entity-converter.js';
import exportJDLObject from '../exporters/jdl-exporter.js';
import { JSONEntity, JSONRootObject, PostProcessedJSONGeneratorJhipsterContent, PostProcessedJSONRootObject } from './types.js';
import { JSONEntity, YoRCJSONObject, PostProcessedJSONGeneratorJhipsterContent, PostProcessedJSONRootObject } from './types.js';
import { removeFieldsWithNullishValues } from '../../generators/base/support/config.js';
import { GENERATOR_JHIPSTER } from '../../generators/generator-constants.js';
import JDLApplication from '../models/jdl-application.js';
Expand All @@ -44,7 +44,7 @@ export default {
export function convertToJDL(directory = '.', output: string | false = 'app.jdl'): JDLObject | undefined {
let jdlObject: JDLObject;
if (doesFileExist(path.join(directory, '.yo-rc.json'))) {
const yoRcFileContent: JSONRootObject = readJSONFile(path.join(directory, '.yo-rc.json'));
const yoRcFileContent: YoRCJSONObject = readJSONFile(path.join(directory, '.yo-rc.json'));
let entities: Map<string, JSONEntity> | undefined;
if (doesDirectoryExist(path.join(directory, '.jhipster'))) {
entities = getJSONEntityFiles(directory);
Expand All @@ -64,7 +64,7 @@ export function convertToJDL(directory = '.', output: string | false = 'app.jdl'
return jdlObject;
}

export function convertSingleContentToJDL(yoRcFileContent: JSONRootObject, entities?: Map<string, JSONEntity>): string {
export function convertSingleContentToJDL(yoRcFileContent: YoRCJSONObject, entities?: Map<string, JSONEntity>): string {
return getJDLObjectFromSingleApplication(yoRcFileContent, entities).toString();
}

Expand All @@ -76,7 +76,7 @@ function getJDLObjectFromMultipleApplications(directory: string): JDLObject {
let jdlObject = new JDLObject();
subDirectories.forEach(subDirectory => {
const applicationDirectory = path.join(directory, subDirectory);
const yoRcFileContent: JSONRootObject = readJSONFile(path.join(applicationDirectory, '.yo-rc.json'));
const yoRcFileContent: YoRCJSONObject = readJSONFile(path.join(applicationDirectory, '.yo-rc.json'));
let entities: Map<string, JSONEntity> = new Map();
if (doesDirectoryExist(path.join(applicationDirectory, '.jhipster'))) {
entities = getJSONEntityFiles(applicationDirectory);
Expand All @@ -87,7 +87,7 @@ function getJDLObjectFromMultipleApplications(directory: string): JDLObject {
}

export function getJDLObjectFromSingleApplication(
yoRcFileContent: JSONRootObject,
yoRcFileContent: YoRCJSONObject,
entities?: Map<string, JSONEntity>,
existingJDLObject = new JDLObject(),
): JDLObject {
Expand All @@ -103,7 +103,7 @@ export function getJDLObjectFromSingleApplication(
return mergeJDLObjects(existingJDLObject, jdlObject);
}

function cleanYoRcFileContent(yoRcFileContent: JSONRootObject): PostProcessedJSONRootObject {
function cleanYoRcFileContent(yoRcFileContent: YoRCJSONObject): PostProcessedJSONRootObject {
for (const key of Object.keys(yoRcFileContent)) {
yoRcFileContent[key] = removeFieldsWithNullishValues(yoRcFileContent[key]);
}
Expand Down
4 changes: 2 additions & 2 deletions jdl/converters/json-to-jdl-entity-converter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ function convertJSONToJDLValidation(rule: string, field: JSONField): JDLValidati
}

function addEnumsToJDL(entity: JSONEntity): void {
entity?.fields?.forEach(field => {
entity?.fields?.forEach((field: JSONField) => {
if (field.fieldValues !== undefined) {
jdlObject.addEnum(
new JDLEnum({
Expand All @@ -145,7 +145,7 @@ function addEnumsToJDL(entity: JSONEntity): void {
});
}

function getEnumValuesFromString(valuesAsString: string): any {
function getEnumValuesFromString(valuesAsString: string): any[] {
return valuesAsString.split(',').map(fieldValue => {
// if fieldValue looks like ENUM_VALUE (something)
if (fieldValue.includes('(')) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,11 @@ describe('jdl - DeploymentConverter', () => {
"directoryPath": "../",
"dockerPushCommand": "docker push",
"dockerRepositoryName": "test",
"gatewayType": undefined,
"ingressDomain": undefined,
"ingressType": undefined,
"istio": undefined,
"kubernetesServiceType": undefined,
"monitoring": "no",
"openshiftNamespace": "default",
"registryReplicas": 2,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ describe('jdl - EnumConverter', () => {
describe('convertEnums', () => {
describe('when not passing enumerations', () => {
it('should fail', () => {
// @ts-expect-error
expect(() => convertEnums()).toThrow(/^Enumerations have to be passed so as to be converted.$/);
});
});
Expand Down
2 changes: 1 addition & 1 deletion jdl/converters/parsed-jdl-to-jdl-object/enum-converter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export default { convertEnums };
* @param {Array} enumerations - parsed JDL enumerations.
* @return the converted JDLEnums.
*/
export function convertEnums(enumerations): JDLEnum[] {
export function convertEnums(enumerations?: ParsedJDLEnum[]): JDLEnum[] {
Tcharl marked this conversation as resolved.
Show resolved Hide resolved
if (!enumerations) {
throw new Error('Enumerations have to be passed so as to be converted.');
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

import { before, it, describe, expect } from 'esmocha';
import { convertField } from './field-converter.js';
import JDLField from '../../models/jdl-field.js';

describe('jdl - FieldConverter', () => {
describe('convertField', () => {
Expand All @@ -36,7 +37,6 @@ describe('jdl - FieldConverter', () => {
convertedField = convertField({
name: 'anAwesomeField',
type: 'String',
comment: 'An awesome comment!',
});
});

Expand All @@ -56,7 +56,7 @@ JDLField {
let nameFromConvertedField;

before(() => {
const convertedField = convertField({
const convertedField: JDLField = convertField({
name: 'AnAwesomeField',
type: 'String',
});
Expand Down
3 changes: 2 additions & 1 deletion jdl/converters/parsed-jdl-to-jdl-object/field-converter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import JDLField from '../../models/jdl-field.js';
import { formatComment } from '../../utils/format-utils.js';
import { lowerFirst } from '../../utils/string-utils.js';
import { ParsedJDLEntityField } from './types.js';

export default { convertField };

Expand All @@ -28,7 +29,7 @@ export default { convertField };
* @param {Object} field - a parsed JDL field.
* @return the converted JDLField.
*/
export function convertField(field): JDLField {
export function convertField(field: ParsedJDLEntityField): JDLField {
if (!field) {
throw new Error('A field has to be passed so as to be converted.');
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -581,8 +581,13 @@ JDLDeployment {
"directoryPath": "../",
"dockerRepositoryName": "test",
"gatewayType": "SpringCloudGateway",
"ingressDomain": undefined,
"ingressType": undefined,
"istio": undefined,
"kubernetesServiceType": undefined,
"monitoring": "no",
"serviceDiscoveryType": "consul",
"storageType": undefined,
}
`);
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ import {
} from './types.js';
import JDLApplication from '../../models/jdl-application.js';
import JDLField from '../../models/jdl-field.js';
import JDLValidation from '../../models/jdl-validation.js';
import { JDLEntity } from '../../models/index.js';

let parsedContent: ParsedJDLApplications;
let configuration: ParsedJDLRoot;
Expand Down Expand Up @@ -103,45 +105,45 @@ function fillDeployments(): void {
});
}

function fillEnums() {
function fillEnums(): void {
const jdlEnums = convertEnums(parsedContent.enums);
jdlEnums.forEach(jdlEnum => {
jdlObject.addEnum(jdlEnum);
});
}

function fillClassesAndFields() {
const jdlEntities = convertEntities(parsedContent.entities, getJDLFieldsFromParsedEntity);
function fillClassesAndFields(): void {
const jdlEntities: JDLEntity[] = convertEntities(parsedContent.entities, getJDLFieldsFromParsedEntity);
jdlEntities.forEach(jdlEntity => {
jdlObject.addEntity(jdlEntity);
});
}

function getJDLFieldsFromParsedEntity(entity: ParsedJDLEntity): JDLField[] {
const fields: any[] = [];
const fields: JDLField[] = [];
const arr = entity.body || [];
for (let i = 0; i < arr.length; i++) {
const field = arr[i];
const jdlField = convertField(field);
jdlField.validations = getValidations(field);
jdlField.options = convertAnnotationsToOptions(field.annotations);
jdlField.options = convertAnnotationsToOptions(field.annotations || []);
fields.push(jdlField);
}
return fields;
}

function getValidations(field: ParsedJDLEntityField) {
function getValidations(field: ParsedJDLEntityField): Record<string, JDLValidation> {
return convertValidations(field.validations, getConstantValueFromConstantName).reduce((jdlValidations, jdlValidation) => {
jdlValidations[jdlValidation.name] = jdlValidation;
return jdlValidations;
}, {});
}

function getConstantValueFromConstantName(constantName: string) {
function getConstantValueFromConstantName(constantName: string): string {
return parsedContent.constants[constantName];
}

function fillAssociations() {
function fillAssociations(): void {
const jdlRelationships = convertRelationships(parsedContent.relationships, convertAnnotationsToOptions);
jdlRelationships.forEach(jdlRelationship => {
// TODO: addRelationship only expects one argument.
Expand Down Expand Up @@ -173,15 +175,15 @@ function convertAnnotationsToOptions(
return result;
}

function fillOptions() {
function fillOptions(): void {
if (configuration.applicationType === applicationTypes.MICROSERVICE && !parsedContent.options.microservice) {
globallyAddMicroserviceOption(configuration.applicationName);
globallyAddMicroserviceOption(configuration.applicationName!);
}
fillUnaryAndBinaryOptions();
}

// TODO: move it to another file? it may not be the parser's responsibility to do it
function globallyAddMicroserviceOption(applicationName) {
function globallyAddMicroserviceOption(applicationName: string): void {
jdlObject.addOption(
new JDLBinaryOption({
name: binaryOptions.Options.MICROSERVICE,
Expand All @@ -191,7 +193,7 @@ function globallyAddMicroserviceOption(applicationName) {
);
}

function fillUnaryAndBinaryOptions() {
function fillUnaryAndBinaryOptions(): void {
// TODO: move it to another file? it may not be the parser's responsibility to do it
if (configuration.applicationType === applicationTypes.MICROSERVICE) {
jdlObject.addOption(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ describe('jdl - RelationshipConverter', () => {
},
},
],
// @ts-expect-error
options => {
if (options.length !== 0) {
return { builtInEntity: true };
Expand Down Expand Up @@ -116,6 +117,7 @@ describe('jdl - RelationshipConverter', () => {
},
},
],
// @ts-expect-error
options => {
if (options.length !== 0) {
return { builtInEntity: true };
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import JDLRelationship from '../../models/jdl-relationship.js';
import { lowerFirst } from '../../utils/string-utils.js';
import { formatComment } from '../../utils/format-utils.js';
import { asJdlRelationshipType } from '../../jhipster/relationship-types.js';
import { ParsedJDLRelationship } from './types.js';
import { ParsedJDLAnnotation, ParsedJDLRelationship } from './types.js';

export default { convertRelationships };

Expand All @@ -31,7 +31,12 @@ export default { convertRelationships };
* @param {Function} annotationToOptionConverter - the function that can convert annotations to options.
* @return the converted JDL relationships.
*/
export function convertRelationships(parsedRelationships: ParsedJDLRelationship[], annotationToOptionConverter): JDLRelationship[] {
export function convertRelationships(
parsedRelationships: ParsedJDLRelationship[],
annotationToOptionConverter: (
annotations: ParsedJDLAnnotation[],
) => Record<string, boolean | string | number | string[] | boolean[] | number[]>,
): JDLRelationship[] {
if (!parsedRelationships) {
throw new Error('Relationships have to be passed so as to be converted.');
}
Expand Down
7 changes: 5 additions & 2 deletions jdl/converters/parsed-jdl-to-jdl-object/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,11 @@ export type ParsedJDLValidation = {
};

export type ParsedJDLEntityField = {
annotations: ParsedJDLAnnotation[];
validations: ParsedJDLValidation[];
annotations?: ParsedJDLAnnotation[];
validations?: ParsedJDLValidation[];
name: string;
type: string;
documentation?: string;
};

export type ParsedJDLEntity = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ describe('jdl - ValidationConverter', () => {
describe('convertValidations', () => {
describe('when not passing validations', () => {
it('should fail', () => {
// @ts-expect-error
expect(() => convertValidations()).toThrow(/^Validations have to be passed so as to be converted.$/);
});
});
Expand Down
10 changes: 5 additions & 5 deletions jdl/converters/parsed-jdl-to-jdl-object/validation-converter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,15 +34,15 @@ export default { convertValidations };
* @return the converted JDLValidations.
*/
export function convertValidations(
validations: ParsedJDLValidation[],
constantValueGetter: (constant: string) => string | number | boolean | RegExp,
validations?: ParsedJDLValidation[],
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not optional

Suggested change
validations?: ParsedJDLValidation[],
validations: ParsedJDLValidation[],

constantValueGetter?: (constant: string) => string | number | boolean | RegExp,
): JDLValidation[] {
if (!validations) {
throw new Error('Validations have to be passed so as to be converted.');
}
return validations.reduce((jdlValidations: JDLValidation[], parsedValidation: ParsedJDLValidation) => {
if (parsedValidation) {
jdlValidations = [...jdlValidations, convertValidation(parsedValidation, constantValueGetter)];
jdlValidations = [...jdlValidations, convertValidation(parsedValidation, constantValueGetter!)];
}
return jdlValidations;
}, []);
Expand All @@ -63,15 +63,15 @@ function convertValidation(
value = constantValueGetter.call(undefined, value as string);
}
if (validation.key === PATTERN) {
value = formatThePatternValidationValue(value);
value = formatThePatternValidationValue(value as string);
}
return new JDLValidation({
name: validation.key,
value,
});
}

function formatThePatternValidationValue(value) {
function formatThePatternValidationValue(value: string): string {
if (!value.includes("'")) {
return value;
}
Expand Down
10 changes: 7 additions & 3 deletions jdl/converters/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,10 @@ export type JSONBlueprint = {
export type JSONMicrofrontend = {
baseName: string;
};

export type JSONGeneratorJhipsterContentDeployment = {
appsFolders?: string[];
clusteredDbApps?: string[];
};
export type JSONGeneratorJhipsterContent = {
baseName: string;
applicationType?: string;
Expand Down Expand Up @@ -74,7 +77,8 @@ export type JSONGeneratorJhipsterContent = {
promptValues?: Partial<JSONGeneratorJhipsterContent>;
blueprints?: JSONBlueprint[] | null;
microfrontends?: JSONMicrofrontend[] | null;
} & Record<string, any>;
} & JSONGeneratorJhipsterContentDeployment &
Record<string, any>;

export type PostProcessedJSONGeneratorJhipsterContent = Omit<
JSONGeneratorJhipsterContent,
Expand All @@ -88,6 +92,6 @@ export type PostProcessedJSONRootObject = {
[GENERATOR_JHIPSTER]: PostProcessedJSONGeneratorJhipsterContent;
};

Tcharl marked this conversation as resolved.
Show resolved Hide resolved
export type JSONRootObject = {
export type YoRCJSONObject = {
Tcharl marked this conversation as resolved.
Show resolved Hide resolved
[GENERATOR_JHIPSTER]: JSONGeneratorJhipsterContent;
};
10 changes: 6 additions & 4 deletions jdl/exporters/config.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import { GENERATOR_NAME } from './export-utils.js';
import { YoRCJSONObject } from '../converters/types.js';

export const mergeYoRcContent = (oldConfig: Record<string, Record<string, any>>, newConfig: Record<string, Record<string, any>>) => {
const merged: Record<string, Record<string, any>> = { [GENERATOR_NAME]: {} };
export const mergeYoRcContent = (oldConfig: YoRCJSONObject, newConfig: YoRCJSONObject): YoRCJSONObject => {
// @ts-expect-error partial assignment
const merged: Partial<YoRCJSONObject> = { [GENERATOR_NAME]: {} };
for (const ns of new Set([...Object.keys(oldConfig), ...Object.keys(newConfig)])) {
merged[ns] = { ...oldConfig[ns], ...newConfig[ns] };
}
if (oldConfig[GENERATOR_NAME]?.creationTimestamp) {
merged[GENERATOR_NAME].creationTimestamp = oldConfig[GENERATOR_NAME].creationTimestamp;
merged[GENERATOR_NAME]!.creationTimestamp = oldConfig[GENERATOR_NAME].creationTimestamp;
}
return merged;
return merged as YoRCJSONObject;
};
Loading
Loading