Skip to content

Commit

Permalink
use derived constants in entity-server templates and domain
Browse files Browse the repository at this point in the history
  • Loading branch information
Tcharl committed Apr 12, 2021
1 parent 05970e0 commit 8b85818
Show file tree
Hide file tree
Showing 21 changed files with 578 additions and 555 deletions.
29 changes: 18 additions & 11 deletions generators/entity-server/files.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,13 @@ const chalk = require('chalk');
const fs = require('fs');
const utils = require('../utils');
const constants = require('../generator-constants');
const { CASSANDRA, COUCHBASE, MONGODB, NEO4J, SQL } = require('../../jdl/jhipster/database-types');
const { ELASTICSEARCH } = require('../../jdl/jhipster/search-engine-types');
const { MapperTypes, ServiceTypes } = require('../../jdl/jhipster/entity-options');
const { EHCACHE, CAFFEINE, INFINISPAN, REDIS } = require('../../jdl/jhipster/cache-types');

const { MAPSTRUCT } = MapperTypes;
const { SERVICE_CLASS, SERVICE_IMPL } = ServiceTypes;

/* Constants use throughout */
const INTERPOLATE_REGEX = constants.INTERPOLATE_REGEX;
Expand All @@ -36,7 +43,7 @@ const SERVER_TEST_SRC_DIR = constants.SERVER_TEST_SRC_DIR;
const serverFiles = {
dbChangelog: [
{
condition: generator => generator.databaseType === 'cassandra' && !generator.skipDbChangelog,
condition: generator => generator.databaseType === CASSANDRA && !generator.skipDbChangelog,
path: SERVER_MAIN_RES_DIR,
templates: [
{
Expand All @@ -46,7 +53,7 @@ const serverFiles = {
],
},
{
condition: generator => generator.searchEngine === 'couchbase' && !generator.skipDbChangelog,
condition: generator => generator.searchEngine === COUCHBASE && !generator.skipDbChangelog,
path: SERVER_MAIN_RES_DIR,
templates: [
{
Expand Down Expand Up @@ -91,7 +98,7 @@ const serverFiles = {
],
},
{
condition: generator => generator.searchEngine === 'elasticsearch' && !generator.embedded,
condition: generator => generator.searchEngine === ELASTICSEARCH && !generator.embedded,
path: SERVER_MAIN_SRC_DIR,
templates: [
{
Expand Down Expand Up @@ -121,7 +128,7 @@ const serverFiles = {
],
},
{
condition: generator => generator.reactive && generator.databaseType === 'sql' && !generator.embedded,
condition: generator => generator.reactive && generator.databaseType === SQL && !generator.embedded,
path: SERVER_MAIN_SRC_DIR,
templates: [
{
Expand All @@ -135,7 +142,7 @@ const serverFiles = {
],
},
{
condition: generator => generator.service === 'serviceImpl' && !generator.embedded,
condition: generator => generator.service === SERVICE_IMPL && !generator.embedded,
path: SERVER_MAIN_SRC_DIR,
templates: [
{
Expand All @@ -149,7 +156,7 @@ const serverFiles = {
],
},
{
condition: generator => generator.service === 'serviceClass' && !generator.embedded,
condition: generator => generator.service === SERVICE_CLASS && !generator.embedded,
path: SERVER_MAIN_SRC_DIR,
templates: [
{
Expand All @@ -159,7 +166,7 @@ const serverFiles = {
],
},
{
condition: generator => generator.dto === 'mapstruct',
condition: generator => generator.dto === MAPSTRUCT,
path: SERVER_MAIN_SRC_DIR,
templates: [
{
Expand Down Expand Up @@ -228,7 +235,7 @@ const serverFiles = {
],
},
{
condition: generator => generator.dto === 'mapstruct',
condition: generator => generator.dto === MAPSTRUCT,
path: SERVER_TEST_SRC_DIR,
templates: [
{
Expand All @@ -238,7 +245,7 @@ const serverFiles = {
],
},
{
condition: generator => generator.dto === 'mapstruct' && ['sql', 'mongodb', 'couchbase', 'neo4j'].includes(generator.databaseType),
condition: generator => generator.dto === MAPSTRUCT && [SQL, MONGODB, COUCHBASE, NEO4J].includes(generator.databaseType),
path: SERVER_TEST_SRC_DIR,
templates: [
{
Expand Down Expand Up @@ -305,8 +312,8 @@ function writeFiles() {
}

function customizeFiles() {
if (this.databaseType === 'sql') {
if (['ehcache', 'caffeine', 'infinispan', 'redis'].includes(this.cacheProvider) && this.enableHibernateCache) {
if (this.databaseType === SQL) {
if ([EHCACHE, CAFFEINE, INFINISPAN, REDIS].includes(this.cacheProvider) && this.enableHibernateCache) {
this.addEntityToCache(this.asEntity(this.entityClass), this.relationships, this.packageName, this.packageFolder, this.cacheProvider);
}
}
Expand Down
11 changes: 7 additions & 4 deletions generators/entity-server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ const constants = require('../generator-constants');
const { writeFiles, customizeFiles } = require('./files');
const utils = require('../utils');
const BaseBlueprintGenerator = require('../generator-base-blueprint');
const { GENERATOR_ENTITY_SERVER } = require('../generator-list');
const { OAUTH2, SESSION } = require('../../jdl/jhipster/authentication-types');
const { SQL } = require('../../jdl/jhipster/database-types');
const { isReservedTableName } = require('../../jdl/jhipster/reserved-keywords');

/* constants used throughout */
Expand All @@ -34,7 +37,7 @@ module.exports = class extends BaseBlueprintGenerator {

this.jhipsterContext = opts.jhipsterContext || opts.context;

useBlueprints = !this.fromBlueprint && this.instantiateBlueprints('entity-server', { context: opts.context });
useBlueprints = !this.fromBlueprint && this.instantiateBlueprints(GENERATOR_ENTITY_SERVER, { context: opts.context });
}

// Public API method used by the getter and also by Blueprints
Expand Down Expand Up @@ -79,7 +82,7 @@ module.exports = class extends BaseBlueprintGenerator {
loadConfigIntoGenerator() {
utils.copyObjectProps(this, this.entity);

this.testsNeedCsrf = ['oauth2', 'session'].includes(this.entity.authenticationType);
this.testsNeedCsrf = [OAUTH2, SESSION].includes(this.entity.authenticationType);
this.officialDatabaseType = constants.OFFICIAL_DATABASE_TYPE_NAMES[this.entity.databaseType];
},

Expand Down Expand Up @@ -118,7 +121,7 @@ module.exports = class extends BaseBlueprintGenerator {
if (this.primaryKey && this.primaryKey.derived) {
this.isUsingMapsId = true;
this.mapsIdAssoc = this.relationships.find(rel => rel.id);
this.hasOauthUser = this.mapsIdAssoc.otherEntityName === 'user' && this.authenticationType === 'oauth2';
this.hasOauthUser = this.mapsIdAssoc.otherEntityName === 'user' && this.authenticationType === OAUTH2;
} else {
this.isUsingMapsId = false;
this.mapsIdAssoc = null;
Expand Down Expand Up @@ -171,7 +174,7 @@ module.exports = class extends BaseBlueprintGenerator {
}

_generateSqlSafeName(name) {
if (isReservedTableName(name, 'sql')) {
if (isReservedTableName(name, SQL)) {
return `e_${name}`;
}
return name;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
limitations under the License.
-%>
// Initialize the database
<%_ if (primaryKey.type === 'UUID' && databaseType !== 'sql') { _%>
<%_ if (primaryKey.isUuid && !databaseTypeSql) { _%>
<%= persistInstance %>.set<%= primaryKey.nameCapitalized %>(UUID.randomUUID());
<%_ } _%>
<%= entityInstance %>Repository.<%= saveMethod %>(<%= persistInstance %>)<%= callBlock %>;
Expand All @@ -33,14 +33,14 @@ partialUpdated<%= persistClass %>.set<%= primaryKey.nameCapitalized %>(<%= persi
.<%= field.fieldName %>(<%= 'UPDATED_' + field.fieldNameUnderscored.toUpperCase() %>)<% if (field.fieldWithContentType) { %>
.<%= field.fieldName %>ContentType(<%= 'UPDATED_' + field.fieldNameUnderscored.toUpperCase() %>_CONTENT_TYPE)<% } %><% } %>;
<%_ } else { _%>
<%_ for (field of fieldsToUpdate) { _%>
<%_ for (field of fieldsToUpdate) { _%>
<%_ if (field.includeField) { %>
partialUpdated<%= persistClass %>.set<%= field.fieldInJavaBeanMethod %>(<%= field.updateWithValue %>);
<%_ if (field.fieldWithContentType) { _%>
<%_ if (field.fieldWithContentType) { _%>
partialUpdated<%= persistClass %>.set<%= field.fieldInJavaBeanMethod %>ContentType(<%= field.updateWithValue %>_CONTENT_TYPE);
<%_ } _%>
<%_ } _%>
<%_ } _%>
<%_ } _%>
<%_ } _%>
<%_ } _%>
<%_ if (!reactive) { _%>
Expand All @@ -60,19 +60,21 @@ webTestClient
<%_ } _%>

// Validate the <%= entityClass %> in the database
<%_ if (databaseType === 'couchbase') { _%>
<%_ if (databaseTypeCouchbase) { _%>
SecurityContextHolder.setContext(TestSecurityContextHolder.getContext());
<%_ } _%>
List<<%= persistClass %>> <%= entityInstance %>List = <%= entityInstance %>Repository.findAll()<%= callListBlock %>;
assertThat(<%= entityInstance %>List).hasSize(databaseSizeBeforeUpdate);
<%= persistClass %> test<%= entityClass %> = <%= entityInstance %>List.get(<%= entityInstance %>List.size() - 1);
<%_ for (field of fields) { if (field.fieldType === 'ZonedDateTime') { _%>
<%_ for (field of fields) { _%>
<%_ if (field.fieldTypeZonedDateTime) { _%>
assertThat(test<%= entityClass %>.get<%= field.fieldInJavaBeanMethod %>()).isEqualTo(<%= field.testWithConstant %>);
<%_ } else if ((field.fieldType === 'byte[]' || field.fieldType === 'ByteBuffer') && field.fieldTypeBlobContent !== 'text') { _%>
<%_ } else if (field.fieldTypeBinary && !field.blobContentTypeText) { _%>
assertThat(test<%= entityClass %>.get<%= field.fieldInJavaBeanMethod %>()).isEqualTo(<%= field.testWithConstant %>);
assertThat(test<%= entityClass %>.get<%= field.fieldInJavaBeanMethod %>ContentType()).isEqualTo(<%= field.testWithConstant %>_CONTENT_TYPE);
<%_ } else if (field.fieldType === 'BigDecimal'){ _%>
<%_ } else if (field.fieldTypeBigDecimal) { _%>
assertThat(test<%= entityClass %>.get<%= field.fieldInJavaBeanMethod %>()).isEqualByComparingTo(<%= field.testWithConstant %>);
<%_ } else { _%>
<%_ } else { _%>
assertThat(test<%= entityClass %>.get<%= field.fieldInJavaBeanMethod %>()).isEqualTo(<%= field.testWithConstant %>);
<%_ } } _%>
<%_ } _%>
<%_ } _%>
45 changes: 23 additions & 22 deletions generators/entity-server/templates/partials/save_template.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ const mapper = entityInstance + 'Mapper';
const dtoToEntity = mapper + '.' + 'toEntity';
const entityToDto = mapper + '.' + 'toDto';
const entityToDtoReference = mapper + '::' + 'toDto';
const returnPrefix = (returnDirectly && searchEngine !== 'elasticsearch') ? 'return' : instanceType + ' result =';
const returnPrefix = (returnDirectly && !searchEngine) ? 'return' : instanceType + ' result =';
let resultEntity;
let mapsIdEntityInstance;
let mapsIdRepoInstance;
Expand All @@ -32,39 +32,40 @@ if (isUsingMapsId === true) {
mapsIdEntityInstance = mapsIdAssoc.otherEntityNameCapitalized.charAt(0).toLowerCase() + mapsIdAssoc.otherEntityNameCapitalized.slice(1);
mapsIdRepoInstance = `${mapsIdEntityInstance}Repository`;
otherEntityName = mapsIdAssoc.otherEntityName;
if (isController === true) { _%>
if (isController === true) { _%>
if (Objects.isNull(<%= instanceName %>.get<%= mapsIdAssoc.relationshipNameCapitalized %>())) {
throw new BadRequestAlertException("Invalid association value provided", ENTITY_NAME, "null");
}
<%_ } _%>
<%_ }
if (!viaService) {
if (dto === 'mapstruct') {
<%_ } _%>
<%_ } _%>
<%_ if (!viaService) { _%>
<%_ if (dtoMapstruct) { _%>
resultEntity = persistInstance; _%>
<%= persistClass %> <%= persistInstance %> = <%= dtoToEntity %>(<%= instanceName %>);
<%_ if (isUsingMapsId === true) { _%>
<%_ if (isUsingMapsId === true) { _%>
<%= mapsIdAssoc.otherEntity.primaryKey.type %> <%= otherEntityName %>Id = <%= instanceName %>.get<%= mapsIdAssoc.relationshipNameCapitalized %>().get<%= primaryKey.nameCapitalized %>();
<%= mapsIdRepoInstance %>.findById(<%= otherEntityName %>Id).ifPresent(<%= persistInstance %>::<%_ if (fluentMethods === false) { _%>set<%= mapsIdAssoc.relationshipNameCapitalized %> <%_ } else { _%><%= mapsIdAssoc.relationshipName %><%_ } _%>);
<%_ } _%>
<%= mapsIdRepoInstance %>.findById(<%= otherEntityName %>Id).ifPresent(<%= persistInstance %>::<%_ if (!fluentMethods) { _%>set<%= mapsIdAssoc.relationshipNameCapitalized %> <%_ } else { _%><%= mapsIdAssoc.relationshipName %><%_ } _%>);
<%_ } _%>
<%= persistInstance %> = <%= entityInstance %>Repository.save(<%= persistInstance %>);
<%= returnPrefix %> <%= entityToDto %>(<%= persistInstance %>);
<%_ } else { resultEntity = 'result'; _%>
<%_ if (isUsingMapsId === true) { _%>
<%_ } else {
resultEntity = 'result'; _%>
<%_ if (isUsingMapsId) { _%>
<%= mapsIdAssoc.otherEntity.primaryKey.type %> <%= otherEntityName %>Id = <%= instanceName %>.get<%= mapsIdAssoc.relationshipNameCapitalized %>().get<%= primaryKey.nameCapitalized %>();
<%= mapsIdRepoInstance %>.findById(<%= otherEntityName %>Id).ifPresent(<%= instanceName %>::<%_ if (fluentMethods === false) { _%>set<%= mapsIdAssoc.relationshipNameCapitalized %> <%_ } else { _%><%= otherEntityName %><%_ } _%>);
<%_ } _%>
<%= mapsIdRepoInstance %>.findById(<%= otherEntityName %>Id).ifPresent(<%= instanceName %>::<%_ if (!fluentMethods) { _%>set<%= mapsIdAssoc.relationshipNameCapitalized %> <%_ } else { _%><%= otherEntityName %><%_ } _%>);
<%_ } _%>
<%= returnPrefix %> <%= entityInstance %>Repository.save(<%= persistInstance %>);
<%_ }
if (searchEngine === 'elasticsearch') { _%>
<%_ } _%>
<%_ if (searchEngine) { _%>
<%= entityInstance %>SearchRepository.save(<%= resultEntity %>);
<%_ if (returnDirectly) { _%>
<%_ if (returnDirectly) { _%>
return result;
<%_ }
}
} else { _%>
<%_ if (isUsingMapsId === true && isController === false) { _%>
<%_ } _%>
<%_ } _%>
<%_ } else { _%>
<%_ if (isUsingMapsId === true && isController === false) { _%>
<%= mapsIdAssoc.otherEntity.primaryKey.type %> <%= otherEntityName %>Id = <%= entityInstance %>.get<%= mapsIdAssoc.relationshipNameCapitalized %>().get<%= primaryKey.nameCapitalized %>();
<%= mapsIdRepoInstance %>.findById(<%= otherEntityName %>Id).ifPresent(<%= entityInstance %>::<%_ if (fluentMethods === false) { _%>set<%= mapsIdAssoc.relationshipNameCapitalized %> <%_ } else { _%><%= otherEntityName %><%_ } _%>);
<%_ } _%>
<%= mapsIdRepoInstance %>.findById(<%= otherEntityName %>Id).ifPresent(<%= entityInstance %>::<%_ if (!fluentMethods) { _%>set<%= mapsIdAssoc.relationshipNameCapitalized %> <%_ } else { _%><%= otherEntityName %><%_ } _%>);
<%_ } _%>
<%= returnPrefix %> <%= entityInstance %>Service.save(<%= instanceName %>);
<%_ } _%>
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,11 @@ _%>
<%_ if (viaService) { _%>
return <%= entityInstance %>Service.save(<%= instanceName %>)
<%_ } else { _%>
return <%= entityInstance %>Repository.save(<%if (dto === 'mapstruct') { %><%= dtoToEntity %>(<% } %><%= instanceName %>)<%if (dto === 'mapstruct') { %>)<% } -%>
<%_ if (searchEngine === 'elasticsearch') { %>
return <%= entityInstance %>Repository.save(<%if (dtoMapstruct) { %><%= dtoToEntity %>(<% } %><%= instanceName %>)<%if (dtoMapstruct) { %>)<% } -%>
<%_ if (searchEngineElasticsearch) { %>
.flatMap(<%= entityInstance %>SearchRepository::save)
<%_ } -%>
<%_ if (dto === 'mapstruct') { %>
<%_ if (dtoMapstruct) { %>
.map(<%= entityToDtoReference %>)
<%_ } -%>
<%_ if (returnDirectly) { _%>;<%_ } _%>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,12 @@
limitations under the License.
-%>
<%_ if (reactive) { _%>
return <%= entityInstance %><%= viaService ? 'Service.delete' : 'Repository.deleteById' %>(id)<%_ if (!viaService && searchEngine === 'elasticsearch') { %>
return <%= entityInstance %><%= viaService ? 'Service.delete' : 'Repository.deleteById' %>(id)<%_ if (!viaService && searchEngineElasticsearch) { %>
.then(<%= entityInstance %>SearchRepository.deleteById(id))<%_ } _%><%_ if (!fromResource) { _%>;
<%_ } _%>
<%_ } else { _%>
<%= entityInstance %><%= viaService ? 'Service.delete' : 'Repository.deleteById' %>(id);
<%_ if (!viaService && searchEngine === 'elasticsearch') { _%>
<%_ if (!viaService && searchEngineElasticsearch) { _%>
<%= entityInstance %>SearchRepository.deleteById(id);
<%_ } _%>
<%_ } _%>
<%_ } _%>
Original file line number Diff line number Diff line change
Expand Up @@ -21,22 +21,21 @@
let result = '';
if (field.fieldValidate === true) {
const rules = field.fieldValidateRules;
const validators = [];
const MAX_VALUE = 2147483647;
const isBlob = field.fieldType === 'byte[]';
const isBlob = field.fieldTypeBytes;
if (rules.includes('required') && !isBlob) {
if (field.fieldValidationRequired && !isBlob) {
// reactive tests need a default validation message because lookup is blocking
validators.push('@NotNull' + (reactive ? '(message = "must not be null")' : ''));
}
if (rules.includes('minlength') && !rules.includes('maxlength')) {
if (field.fieldValidationMinLength && !field.fieldValidationMaxLength) {
validators.push('@Size(min = ' + field.fieldValidateRulesMinlength + ')');
}
if (rules.includes('maxlength') && !rules.includes('minlength')) {
if (field.fieldValidationMaxLength && !field.fieldValidationMinLength) {
validators.push('@Size(max = ' + field.fieldValidateRulesMaxlength + ')');
}
if (rules.includes('minlength') && rules.includes('maxlength')) {
if (field.fieldValidationMinLength && field.fieldValidationMaxLength) {
validators.push('@Size(min = ' + field.fieldValidateRulesMinlength + ', max = ' + field.fieldValidateRulesMaxlength + ')');
}
// Not supported anymore because the server can't check the size of the blob before downloading it completely.
Expand All @@ -49,23 +48,23 @@ if (field.fieldValidate === true) {
// if (rules.includes('minbytes') && rules.includes('maxbytes')) {
// validators.push('@Size(min = ' + field.fieldValidateRulesMinbytes + ', max = ' + field.fieldValidateRulesMaxbytes + ')');
// }
if (rules.includes('min')) {
if (field.fieldType === 'Float' || field.fieldType === 'Double' || field.fieldType === 'BigDecimal') {
if (field.fieldValidationMin) {
if (field.fieldTypeFloat || field.fieldTypeDouble || field.fieldTypeBigDecimal) {
validators.push('@DecimalMin(value = "' + field.fieldValidateRulesMin + '")');
} else {
const isLong = (field.fieldValidateRulesMin > MAX_VALUE || field.fieldType == 'Long') ? 'L' : '';
const isLong = (field.fieldValidateRulesMin > MAX_VALUE || field.fieldTypeLong) ? 'L' : '';
validators.push('@Min(value = ' + field.fieldValidateRulesMin + isLong + ')');
}
}
if (rules.includes('max')) {
if (field.fieldType === 'Float' || field.fieldType === 'Double' || field.fieldType === 'BigDecimal') {
if (field.fieldValidationMax) {
if (field.fieldTypeFloat || field.fieldTypeDouble || field.fieldTypeBigDecimal) {
validators.push('@DecimalMax(value = "' + field.fieldValidateRulesMax + '")');
} else {
const isLong = (field.fieldValidateRulesMax > MAX_VALUE || field.fieldType == 'Long') ? 'L' : '';
const isLong = (field.fieldValidateRulesMax > MAX_VALUE || field.fieldTypeLong) ? 'L' : '';
validators.push('@Max(value = ' + field.fieldValidateRulesMax + isLong + ')');
}
}
if (rules.includes('pattern')) {
if (field.fieldValidationPattern) {
validators.push('@Pattern(regexp = "' + field.fieldValidateRulesPatternJava + '")');
}
result = validators.join('\n ');
Expand Down
Loading

0 comments on commit 8b85818

Please sign in to comment.