From e0d7bebe569c758f15493fde9d5bd3d2a808190a Mon Sep 17 00:00:00 2001 From: Markus Glutting Date: Sun, 5 Sep 2021 18:15:44 +0200 Subject: [PATCH] Consider entitySuffix and dtoSuffix refs #209 - Use asDto and asEntity methods provided by JHipster (this ensures that the entitySuffix and dtoSuffix configOptions are used) - Fix error where Instant fieldType did not work with sqlite --- cli/nhipster.js | 0 generators/entity-server/index.js | 11 +++++- .../templates/server/src/domain/entity.ts.ejs | 28 ++++++++------- .../src/repository/entity.repository.ts.ejs | 6 ++-- .../server/src/service/dto/entity.dto.ts.ejs | 8 ++--- .../src/service/mapper/entity.mapper.ts.ejs | 12 +++---- .../server/e2e/account.e2e-spec.ts.ejs | 12 +++---- .../templates/server/e2e/user.e2e-spec.ts.ejs | 14 ++++---- .../server/src/client/request.ts.ejs | 4 +-- .../server/src/domain/user.entity.ts.ejs | 2 +- .../1570200490072-SeedUsersRoles.ts.ejs | 11 +++--- .../src/repository/user.repository.ts.ejs | 6 ++-- .../src/security/guards/roles.guard.ts.ejs | 4 +-- .../server/src/service/auth.service.ts.ejs | 36 +++++++++---------- .../server/src/service/dto/user.dto.ts.ejs | 2 +- .../src/service/mapper/user.mapper.ts.ejs | 12 +++---- .../server/src/service/user.service.ts.ejs | 24 ++++++------- .../src/web/rest/account.controller.ts.ejs | 14 ++++---- .../web/rest/public.user.controller.ts.ejs | 6 ++-- .../src/web/rest/user.controller.ts.ejs | 22 ++++++------ 20 files changed, 123 insertions(+), 111 deletions(-) mode change 100644 => 100755 cli/nhipster.js diff --git a/cli/nhipster.js b/cli/nhipster.js old mode 100644 new mode 100755 diff --git a/generators/entity-server/index.js b/generators/entity-server/index.js index 12bc71eb..2bc23933 100644 --- a/generators/entity-server/index.js +++ b/generators/entity-server/index.js @@ -31,6 +31,15 @@ const dbTypes = { 'byte[]': 'blob' }; +function sanitizeDbType(fieldType, dbType) { + if (dbType === 'sqlite') { + if (fieldType === 'timestamp') { + return 'datetime'; + } + } + return fieldType; +} + module.exports = class extends EntityServerGenerator { constructor(args, opts) { super(args, { fromBlueprint: true, ...opts }); // fromBlueprint variable is important @@ -65,6 +74,6 @@ module.exports = class extends EntityServerGenerator { } addDbType(fieldType) { - return dbTypes[fieldType]; + return sanitizeDbType(dbTypes[fieldType], this.devDatabaseType); } }; diff --git a/generators/entity-server/templates/server/src/domain/entity.ts.ejs b/generators/entity-server/templates/server/src/domain/entity.ts.ejs index 9ddfce87..27d4e93a 100644 --- a/generators/entity-server/templates/server/src/domain/entity.ts.ejs +++ b/generators/entity-server/templates/server/src/domain/entity.ts.ejs @@ -19,11 +19,12 @@ for (idx in fields) { } for (idx in relationships) { const relationship = relationships[idx]; - if (relationship.otherEntityAngularName === 'User'){ + const otherEntityClass = asEntity(relationship.otherEntity.entityClass); + if (relationship.otherEntity.entityClass === 'User'){ isUserRelationship = true; } - else if (!uniqueEntities[relationship.otherEntityAngularName] && relationship.otherEntityAngularName != asEntity(entityClass)) { - uniqueEntities[relationship.otherEntityAngularName] = relationship.otherEntityFileName; + else if (!uniqueEntities[otherEntityClass] && otherEntityClass != asEntity(entityClass)) { + uniqueEntities[otherEntityClass] = relationship.otherEntityFileName; } } _%> @@ -36,7 +37,7 @@ import { <%= enumClass %> } from './enumeration/<%= uniqueEnums[enumClass] %>'; <%_ }); _%> <%_ if (isUserRelationship === true) { _%> -import { User } from './user.entity'; +import { <%= asEntity('User') %> } from './user.entity'; <%_ } _%> <%_ if (typeof javadoc == 'undefined') { _%> @@ -109,21 +110,22 @@ export class <%= asEntity(entityClass) %> extends BaseEntity { const relationshipRequired = relationships[idx].relationshipRequired; const otherEntityNameCapitalized = relationships[idx].otherEntityNameCapitalized; const ownerSide = relationships[idx].ownerSide; // before was ownerSide === true in and userRel many-to-one + const otherEntityClass = asEntity(relationships[idx].otherEntity.entityClass); let userRelationship = false; - if (relationship.otherEntityAngularName === 'User'){ + if (otherEntityClass === 'User'){ userRelationship = true; } if (relationshipType === 'one-to-many') {_%> - @OneToMany(type => <%= relationship.otherEntityAngularName %> <%_ if (userRelationship === false) { _%>, other => other.<%= otherEntityRelationshipName %><%_ } _%>) - <%= relationshipFieldNamePlural %>: <%= relationship.otherEntityAngularName %>[]; + @OneToMany(type => <%= otherEntityClass %> <%_ if (userRelationship === false) { _%>, other => other.<%= otherEntityRelationshipName %><%_ } _%>) + <%= relationshipFieldNamePlural %>: <%= otherEntityClass %>[]; <%_ } else if (relationshipType === 'many-to-one') { _%> - @ManyToOne(type => <%= relationship.otherEntityAngularName %> <%_ if (!ownerSide && userRelationship === false ) { _%>, other => other.<%= otherEntityRelationshipNamePlural %> <%_ } _%>) - <%= relationshipFieldName %>: <%= relationship.otherEntityAngularName %>; + @ManyToOne(type => <%= otherEntityClass %> <%_ if (!ownerSide && userRelationship === false ) { _%>, other => other.<%= otherEntityRelationshipNamePlural %> <%_ } _%>) + <%= relationshipFieldName %>: <%= otherEntityClass %>; <%_ } else if (relationshipType === 'many-to-many') { _%> - @ManyToMany(type => <%= relationship.otherEntityAngularName %> ) + @ManyToMany(type => <%= otherEntityClass %> ) <%_ if (ownerSide === true) { _%> @JoinTable({ name: '<%= joinTableName %>', @@ -131,12 +133,12 @@ export class <%= asEntity(entityClass) %> extends BaseEntity { inverseJoinColumn: { name: '<%= getColumnName(relationship.relationshipName) %>_id', referencedColumnName: "id" } }) <%_ } _%> - <%= relationshipFieldNamePlural %>: <%= relationship.otherEntityAngularName %>[]; + <%= relationshipFieldNamePlural %>: <%= otherEntityClass %>[]; <%_ } else { _%> - @OneToOne(type => <%= relationship.otherEntityAngularName %>) + @OneToOne(type => <%= otherEntityClass %>) <%_ if (ownerSide === true) { _%>@JoinColumn()<%_ } _%> - <%= relationshipFieldName %>: <%= relationship.otherEntityAngularName %>; + <%= relationshipFieldName %>: <%= otherEntityClass %>; <%_ } } _%> diff --git a/generators/entity-server/templates/server/src/repository/entity.repository.ts.ejs b/generators/entity-server/templates/server/src/repository/entity.repository.ts.ejs index 7b88d7c0..5c5506bf 100644 --- a/generators/entity-server/templates/server/src/repository/entity.repository.ts.ejs +++ b/generators/entity-server/templates/server/src/repository/entity.repository.ts.ejs @@ -1,5 +1,5 @@ import { EntityRepository, Repository } from 'typeorm'; -import { <%= entityClass %> } from '../domain/<%= entityFileName %>.entity'; +import { <%= asEntity(entityClass) %> } from '../domain/<%= entityFileName %>.entity'; -@EntityRepository(<%= entityClass %>) -export class <%= entityClass %>Repository extends Repository<<%= entityClass %>> {} +@EntityRepository(<%= asEntity(entityClass) %>) +export class <%= entityClass %>Repository extends Repository<<%= asEntity(entityClass) %>> {} diff --git a/generators/entity-server/templates/server/src/service/dto/entity.dto.ts.ejs b/generators/entity-server/templates/server/src/service/dto/entity.dto.ts.ejs index a09a93df..7f854dc8 100644 --- a/generators/entity-server/templates/server/src/service/dto/entity.dto.ts.ejs +++ b/generators/entity-server/templates/server/src/service/dto/entity.dto.ts.ejs @@ -25,7 +25,7 @@ for (idx in relationships) { if (relationship.otherEntityAngularName === 'User'){ isUserRelationship = true; } - else if (!uniqueEntities[relationship.otherEntityAngularName] && relationship.otherEntityAngularName != asEntity(entityClass)) { + else if (!uniqueEntities[relationship.otherEntityAngularName] && relationship.otherEntityAngularName != asDto(entityClass)) { uniqueEntities[relationship.otherEntityAngularName] = relationship.otherEntityFileName; } } @@ -39,13 +39,13 @@ import { <%= enumClass %> } from '../../domain/enumeration/<%= uniqueEnums[enumC <%_ }); _%> <%_ if (isUserRelationship === true) { _%> -import { UserDTO } from './user.dto'; +import { <%= asDto('User')%> } from './user.dto'; <%_ } _%> /** - * A <%= asEntity(entityClass) %> DTO object. + * A <%= asDto(entityClass) %> object. */ -export class <%= asEntity(entityClass) %>DTO extends BaseDTO { +export class <%= asDto(entityClass) %> extends BaseDTO { <%_ for (idx in fieldsWithoutId) { const field = fieldsWithoutId[idx]; diff --git a/generators/entity-server/templates/server/src/service/mapper/entity.mapper.ts.ejs b/generators/entity-server/templates/server/src/service/mapper/entity.mapper.ts.ejs index c8993a46..6d458360 100644 --- a/generators/entity-server/templates/server/src/service/mapper/entity.mapper.ts.ejs +++ b/generators/entity-server/templates/server/src/service/mapper/entity.mapper.ts.ejs @@ -1,13 +1,13 @@ import { <%= asEntity(entityClass) %> } from '../../domain/<%= entityFileName %>.entity'; -import { <%= asEntity(entityClass) %>DTO } from '../dto/<%= entityFileName %>.dto'; +import { <%= asDto(entityClass) %> } from '../dto/<%= entityFileName %>.dto'; /** - * A <%= asEntity(entityClass) %> mapper object. + * A <%= entityClass %> mapper object. */ -export class <%= asEntity(entityClass) %>Mapper { +export class <%= entityClass %>Mapper { - static fromDTOtoEntity (entityDTO: <%= asEntity(entityClass) %>DTO): <%= asEntity(entityClass) %> { + static fromDTOtoEntity (entityDTO: <%= asDto(entityClass) %>): <%= asEntity(entityClass) %> { if (!entityDTO) { return; } @@ -20,11 +20,11 @@ export class <%= asEntity(entityClass) %>Mapper { } - static fromEntityToDTO (entity: <%= asEntity(entityClass) %>): <%= asEntity(entityClass) %>DTO { + static fromEntityToDTO (entity: <%= asEntity(entityClass) %>): <%= asDto(entityClass) %> { if (!entity) { return; } - let entityDTO = new <%= asEntity(entityClass) %>DTO(); + let entityDTO = new <%= asDto(entityClass) %>(); const fields = Object.getOwnPropertyNames(entity); diff --git a/generators/server/templates/server/e2e/account.e2e-spec.ts.ejs b/generators/server/templates/server/e2e/account.e2e-spec.ts.ejs index 971f3292..02b9ed52 100644 --- a/generators/server/templates/server/e2e/account.e2e-spec.ts.ejs +++ b/generators/server/templates/server/e2e/account.e2e-spec.ts.ejs @@ -4,7 +4,7 @@ import { AppModule } from '../src/app.module'; import { ExecutionContext, INestApplication } from '@nestjs/common'; import { AuthGuard } from '../src/security/guards/auth.guard'; import { RolesGuard } from '../src/security/guards/roles.guard'; -import { UserDTO } from '../src/service/dto/user.dto'; +import { <%= asDto('User')%> } from '../src/service/dto/user.dto'; import { UserService } from '../src/service/user.service'; import { PasswordChangeDTO } from '../src/service/dto/password-change.dto'; import { AuthService } from '../src/service/auth.service'; @@ -14,7 +14,7 @@ describe('Account', () => { let service: UserService; let authService: AuthService; - const testUserDTO: UserDTO = { + const testUserDTO: <%= asDto('User')%> = { login: 'userTestLogin', email: 'usertest@localhost.it', password: 'testPassword', @@ -33,7 +33,7 @@ describe('Account', () => { newPassword: 'newPassword', }; - let userAuthenticated: UserDTO; + let userAuthenticated: <%= asDto('User')%>; const authGuardMock = { canActivate: (context: ExecutionContext): any => { const req = context.switchToHttp().getRequest(); @@ -63,7 +63,7 @@ describe('Account', () => { }); it('/POST register new user', async () => { - const createdUser: UserDTO = ( + const createdUser: <%= asDto('User')%> = ( await request(app.getHttpServer()) .post('/api/register') .send(testUserDTO) @@ -109,7 +109,7 @@ describe('Account', () => { it('/POST account update settings', async () => { - const savedTestUser: UserDTO = { + const savedTestUser: <%= asDto('User')%> = { firstName: 'updateFirstName', lastName: 'updateLastName', ...testUserAuthenticated, @@ -119,7 +119,7 @@ describe('Account', () => { .send(savedTestUser) .expect(201); - const updatedUserSettings: UserDTO = await service.findByFields({ where: { login: testUserAuthenticated.login } }); + const updatedUserSettings: <%= asDto('User')%> = await service.findByFields({ where: { login: testUserAuthenticated.login } }); expect(updatedUserSettings.firstName).toEqual(savedTestUser.firstName); expect(updatedUserSettings.lastName).toEqual(savedTestUser.lastName); diff --git a/generators/server/templates/server/e2e/user.e2e-spec.ts.ejs b/generators/server/templates/server/e2e/user.e2e-spec.ts.ejs index 6baaf0f3..3e3cb659 100644 --- a/generators/server/templates/server/e2e/user.e2e-spec.ts.ejs +++ b/generators/server/templates/server/e2e/user.e2e-spec.ts.ejs @@ -4,7 +4,7 @@ import { AppModule } from '../src/app.module'; import { INestApplication } from '@nestjs/common'; import { AuthGuard } from '../src/security/guards/auth.guard'; import { RolesGuard } from '../src/security/guards/roles.guard'; -import { UserDTO } from '../src/service/dto/user.dto'; +import { <%= asDto('User')%> } from '../src/service/dto/user.dto'; import { UserService } from '../src/service/user.service'; describe('User', () => { @@ -21,7 +21,7 @@ describe('User', () => { email: 'usertest@localhost.it' }; - const testUserDTO: UserDTO = { + const testUserDTO: <%= asDto('User')%> = { login: 'userTestLogin', firstName: 'UserTest', lastName: 'UserTest', @@ -45,7 +45,7 @@ describe('User', () => { }); it('/POST create user', async () => { - const createdUser: UserDTO = ( + const createdUser: <%= asDto('User')%> = ( await request(app.getHttpServer()) .post('/api/admin/users') .send(testUserRequestObject) @@ -82,16 +82,16 @@ describe('User', () => { expect(updatedUser.firstName).toEqual(savedUser.firstName); <%_ } _%> - await service.delete(savedUser as UserDTO); + await service.delete(savedUser as <%= asDto('User')%>); }); it('/GET user with a login name', async () => { testUserDTO.login = 'TestUserGet'; - const savedUser: UserDTO = await service.save(testUserDTO); + const savedUser: <%= asDto('User')%> = await service.save(testUserDTO); // eslint-disable-next-line @typescript-eslint/no-unused-vars const { password, ...savedUserWithoutPassword } = savedUser; - const getUser: UserDTO = ( + const getUser: <%= asDto('User')%> = ( await request(app.getHttpServer()) .get('/api/admin/users/' + savedUser.login) .expect(200) @@ -108,7 +108,7 @@ describe('User', () => { it('/DELETE user', async () => { testUserDTO.login = 'TestUserDelete'; - const savedUser: UserDTO = await service.save(testUserDTO); + const savedUser: <%= asDto('User')%> = await service.save(testUserDTO); await request(app.getHttpServer()) .delete('/api/admin/users/' + savedUser.login) diff --git a/generators/server/templates/server/src/client/request.ts.ejs b/generators/server/templates/server/src/client/request.ts.ejs index 1efd502b..cb57691d 100644 --- a/generators/server/templates/server/src/client/request.ts.ejs +++ b/generators/server/templates/server/src/client/request.ts.ejs @@ -1,6 +1,6 @@ import { Request as ExpressRequest} from 'express'; -import { UserDTO } from '../service/dto/user.dto'; +import { <%= asDto('User')%> } from '../service/dto/user.dto'; export interface Request extends ExpressRequest { - user?: UserDTO; + user?: <%= asDto('User')%>; } diff --git a/generators/server/templates/server/src/domain/user.entity.ts.ejs b/generators/server/templates/server/src/domain/user.entity.ts.ejs index 34f4cd63..16eb940a 100644 --- a/generators/server/templates/server/src/domain/user.entity.ts.ejs +++ b/generators/server/templates/server/src/domain/user.entity.ts.ejs @@ -4,7 +4,7 @@ import { BaseEntity } from './base/base.entity'; import { Exclude } from 'class-transformer'; @Entity('nhi_user') -export class User extends BaseEntity { +export class <%= asEntity('User') %> extends BaseEntity { @Column({ unique: true }) login: string; @Column({ nullable: true }) diff --git a/generators/server/templates/server/src/migrations/1570200490072-SeedUsersRoles.ts.ejs b/generators/server/templates/server/src/migrations/1570200490072-SeedUsersRoles.ts.ejs index c74dce0b..1318e6b4 100644 --- a/generators/server/templates/server/src/migrations/1570200490072-SeedUsersRoles.ts.ejs +++ b/generators/server/templates/server/src/migrations/1570200490072-SeedUsersRoles.ts.ejs @@ -1,6 +1,7 @@ +<%_ const UserEntity = asEntity('User') %> import { MigrationInterface, QueryRunner, getRepository } from 'typeorm'; <%_ if (authenticationType !== 'oauth2') { _%> -import { User } from '../domain/user.entity'; +import { <%= UserEntity %> } from '../domain/user.entity'; import { transformPassword } from '../security'; <%_ } _%> import { Authority } from '../domain/authority.entity'; @@ -11,7 +12,7 @@ export class SeedUsersRoles1570200490072 implements MigrationInterface { role2: Authority = { name: 'ROLE_USER' }; <%_ if (authenticationType !== 'oauth2') { _%> - user1: User = { + user1: <%= UserEntity %> = { login: 'system', password: 'system', firstName: 'System', @@ -24,7 +25,7 @@ export class SeedUsersRoles1570200490072 implements MigrationInterface { lastModifiedBy: 'system' }; - user2: User = { + user2: <%= UserEntity %> = { login: 'anonymoususer', password: 'anonymoususer', firstName: 'Anonymous', @@ -37,7 +38,7 @@ export class SeedUsersRoles1570200490072 implements MigrationInterface { lastModifiedBy: 'system' }; - user3: User = { + user3: <%= UserEntity %> = { login: 'admin', password: 'admin', firstName: 'Administrator', @@ -50,7 +51,7 @@ export class SeedUsersRoles1570200490072 implements MigrationInterface { lastModifiedBy: 'system' }; - user4: User = { + user4: <%= UserEntity %> = { login: 'user', password: 'user', firstName: 'User', diff --git a/generators/server/templates/server/src/repository/user.repository.ts.ejs b/generators/server/templates/server/src/repository/user.repository.ts.ejs index b7f5c324..08ac16f8 100644 --- a/generators/server/templates/server/src/repository/user.repository.ts.ejs +++ b/generators/server/templates/server/src/repository/user.repository.ts.ejs @@ -1,5 +1,5 @@ import { EntityRepository, Repository } from 'typeorm'; -import { User } from '../domain/user.entity'; +import { <%= asEntity('User') %> } from '../domain/user.entity'; -@EntityRepository(User) -export class UserRepository extends Repository {} +@EntityRepository(<%= asEntity('User') %>) +export class UserRepository extends Repository<<%= asEntity('User') %>> {} diff --git a/generators/server/templates/server/src/security/guards/roles.guard.ts.ejs b/generators/server/templates/server/src/security/guards/roles.guard.ts.ejs index 10e761b1..2cc27fc3 100644 --- a/generators/server/templates/server/src/security/guards/roles.guard.ts.ejs +++ b/generators/server/templates/server/src/security/guards/roles.guard.ts.ejs @@ -1,6 +1,6 @@ import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common'; import { Reflector } from '@nestjs/core'; -import { UserDTO } from '../../service/dto/user.dto'; +import { <%= asDto('User')%> } from '../../service/dto/user.dto'; @Injectable() export class RolesGuard implements CanActivate { @@ -14,7 +14,7 @@ export class RolesGuard implements CanActivate { } const request = context.switchToHttp().getRequest(); - const user = request.user as UserDTO; + const user = request.user as <%= asDto('User')%>; return user && user.authorities && user.authorities.some(role => roles.indexOf(role) >= 0); } diff --git a/generators/server/templates/server/src/service/auth.service.ts.ejs b/generators/server/templates/server/src/service/auth.service.ts.ejs index 7de29152..521af3b7 100644 --- a/generators/server/templates/server/src/service/auth.service.ts.ejs +++ b/generators/server/templates/server/src/service/auth.service.ts.ejs @@ -8,7 +8,7 @@ import * as bcrypt from 'bcrypt'; <%_ } _%> import { AuthorityRepository } from '../repository/authority.repository'; import { UserService } from '../service/user.service'; -import { UserDTO } from './dto/user.dto'; +import { <%= asDto('User')%> } from './dto/user.dto'; import { FindManyOptions } from 'typeorm'; <%_ @@ -53,21 +53,21 @@ export class AuthService { } /* eslint-enable */ - async validateUser(payload: Payload): Promise { + async validateUser(payload: Payload): Promise<<%= asDto('User')%> | undefined> { return await this.findUserWithAuthById(payload.id); } - async findUserWithAuthById(userId: <%= userIdType %>): Promise { + async findUserWithAuthById(userId: <%= userIdType %>): Promise<<%= asDto('User')%> | undefined> { <%_ if (databaseType === 'mongodb') { _%> - const userDTO: UserDTO = await this.userService.findById(userId); + const userDTO: <%= asDto('User')%> = await this.userService.findById(userId); <%_ } else { _%> - const userDTO: UserDTO = await this.userService.findByFields({ where: { id: userId } }); + const userDTO: <%= asDto('User')%> = await this.userService.findByFields({ where: { id: userId } }); <%_ } _%> return userDTO; } - async getAccount(userId: <%= userIdType %>): Promise { - const userDTO: UserDTO = await this.findUserWithAuthById(userId); + async getAccount(userId: <%= userIdType %>): Promise<<%= asDto('User')%> | undefined> { + const userDTO: <%= asDto('User')%> = await this.findUserWithAuthById(userId); if (!userDTO) { return; } @@ -75,7 +75,7 @@ export class AuthService { } async changePassword(userLogin: string, currentClearTextPassword: string, newPassword: string): Promise { - const userFind: UserDTO = await this.userService.findByFields({ where: { login: userLogin } }); + const userFind: <%= asDto('User')%> = await this.userService.findByFields({ where: { login: userLogin } }); if (!userFind) { throw new HttpException('Invalid login name!', HttpStatus.BAD_REQUEST); } @@ -88,8 +88,8 @@ export class AuthService { return; } - async registerNewUser (newUser: UserDTO) : Promise { - let userFind: UserDTO = await this.userService.findByFields({ where: { login: newUser.login} }); + async registerNewUser (newUser: <%= asDto('User')%>) : Promise<<%= asDto('User')%>> { + let userFind: <%= asDto('User')%> = await this.userService.findByFields({ where: { login: newUser.login} }); if (userFind) { throw new HttpException('Login name already used!', HttpStatus.BAD_REQUEST); } @@ -98,16 +98,16 @@ export class AuthService { throw new HttpException('Email is already in use!', HttpStatus.BAD_REQUEST); } newUser.authorities = ['ROLE_USER']; - const user: UserDTO = await this.userService.save(newUser, newUser.login, true); + const user: <%= asDto('User')%> = await this.userService.save(newUser, newUser.login, true); return user; } - async updateUserSettings(userLogin: string, newUserInfo: UserDTO) : Promise { - const userFind: UserDTO = await this.userService.findByFields({ where: { login: userLogin } }); + async updateUserSettings(userLogin: string, newUserInfo: <%= asDto('User')%>) : Promise<<%= asDto('User')%>> { + const userFind: <%= asDto('User')%> = await this.userService.findByFields({ where: { login: userLogin } }); if (!userFind) { throw new HttpException('Invalid login name!', HttpStatus.BAD_REQUEST); } - const userFindEmail: UserDTO = await this.userService.findByFields({ where: { email: newUserInfo.email } }); + const userFindEmail: <%= asDto('User')%> = await this.userService.findByFields({ where: { email: newUserInfo.email } }); if (userFindEmail && newUserInfo.email !== userFind.email) { throw new HttpException('Email is already in use!', HttpStatus.BAD_REQUEST); } @@ -121,11 +121,11 @@ export class AuthService { } <%_ } else if (authenticationType === 'oauth2') { _%> - async findUserOrSave(loginUser: UserDTO): Promise { + async findUserOrSave(loginUser: <%= asDto('User')%>): Promise<<%= asDto('User')%> | undefined> { if (loginUser.login && loginUser.password && !loginUser.email) { loginUser.email = loginUser.login + '@localhost.it'; } - let userFound: UserDTO = await this.userService.findByFields({ where: { login: loginUser.login } }); + let userFound: <%= asDto('User')%> = await this.userService.findByFields({ where: { login: loginUser.login } }); if (!userFound) { const authoritiesName = []; @@ -137,7 +137,7 @@ export class AuthService { return loginUser; } - getAccount(userDTO: UserDTO): any { + getAccount(userDTO: <%= asDto('User')%>): any { if (!userDTO) { return; } @@ -146,7 +146,7 @@ export class AuthService { <%_ } _%> - async getAllUsers(options: FindManyOptions): Promise<[UserDTO[], number]> { + async getAllUsers(options: FindManyOptions<<%= asDto('User')%>>): Promise<[<%= asDto('User')%>[], number]> { return await this.userService.findAndCount(options); } diff --git a/generators/server/templates/server/src/service/dto/user.dto.ts.ejs b/generators/server/templates/server/src/service/dto/user.dto.ts.ejs index bf6db0fc..efd786dd 100644 --- a/generators/server/templates/server/src/service/dto/user.dto.ts.ejs +++ b/generators/server/templates/server/src/service/dto/user.dto.ts.ejs @@ -6,7 +6,7 @@ import { Exclude } from 'class-transformer'; /** * An User DTO object. */ -export class UserDTO extends BaseDTO { +export class <%= asDto('User') %> extends BaseDTO { @ApiModelProperty({ uniqueItems: true, example: 'myuser', description: 'User login' }) @IsString() login: string; diff --git a/generators/server/templates/server/src/service/mapper/user.mapper.ts.ejs b/generators/server/templates/server/src/service/mapper/user.mapper.ts.ejs index 2ae46627..c0cf163f 100644 --- a/generators/server/templates/server/src/service/mapper/user.mapper.ts.ejs +++ b/generators/server/templates/server/src/service/mapper/user.mapper.ts.ejs @@ -1,16 +1,16 @@ -import { User } from '../../domain/user.entity'; -import { UserDTO } from '../dto/user.dto'; +import { <%= asEntity('User') %> } from '../../domain/user.entity'; +import { <%= asDto('User')%> } from '../dto/user.dto'; /** * An User mapper object. */ export class UserMapper { - static fromDTOtoEntity (userDTO: UserDTO): User { + static fromDTOtoEntity (userDTO: <%= asDto('User')%>): <%= asEntity('User') %> { if (!userDTO) { return; } - let user = new User(); + let user = new <%= asEntity('User') %>(); const fields = Object.getOwnPropertyNames(userDTO); fields.forEach(field => { user[field] = userDTO[field]; @@ -19,11 +19,11 @@ export class UserMapper { } - static fromEntityToDTO (user: User): UserDTO { + static fromEntityToDTO (user: <%= asEntity('User') %>): <%= asDto('User')%> { if (!user) { return; } - let userDTO = new UserDTO(); + let userDTO = new <%= asDto('User')%>(); const fields = Object.getOwnPropertyNames(user); diff --git a/generators/server/templates/server/src/service/user.service.ts.ejs b/generators/server/templates/server/src/service/user.service.ts.ejs index 1ca79dcc..54e5bbcb 100644 --- a/generators/server/templates/server/src/service/user.service.ts.ejs +++ b/generators/server/templates/server/src/service/user.service.ts.ejs @@ -1,7 +1,7 @@ import { Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; -import { User } from '../domain/user.entity'; -import { UserDTO } from './dto/user.dto'; +import { <%= asEntity('User') %> } from '../domain/user.entity'; +import { <%= asDto('User')%> } from './dto/user.dto'; import { UserMapper } from './mapper/user.mapper'; import { UserRepository } from '../repository/user.repository'; import { FindManyOptions, FindOneOptions } from 'typeorm'; @@ -11,12 +11,12 @@ import { transformPassword } from '../security'; export class UserService { constructor(@InjectRepository(UserRepository) private userRepository: UserRepository) {} - async findById(id: <%= getPkType(databaseType) === 'Long' ? 'number' : 'string' %>): Promise { + async findById(id: <%= getPkType(databaseType) === 'Long' ? 'number' : 'string' %>): Promise<<%= asDto('User')%> | undefined> { const result = await this.userRepository.findOne(id); return UserMapper.fromEntityToDTO(this.flatAuthorities(result)) } - async findByFields(options: FindOneOptions): Promise { + async findByFields(options: FindOneOptions<<%= asDto('User')%>>): Promise<<%= asDto('User')%> | undefined> { <%_ if (databaseType !== 'mongodb') { _%> options.relations = ['authorities']; <%_ } _%> @@ -24,17 +24,17 @@ export class UserService { return UserMapper.fromEntityToDTO(this.flatAuthorities(result)); } - async find(options: FindManyOptions): Promise { + async find(options: FindManyOptions<<%= asDto('User')%>>): Promise<<%= asDto('User')%> | undefined> { const result = await this.userRepository.findOne(options); return UserMapper.fromEntityToDTO(this.flatAuthorities(result)); } - async findAndCount(options: FindManyOptions): Promise<[UserDTO[], number]> { + async findAndCount(options: FindManyOptions<<%= asDto('User')%>>): Promise<[<%= asDto('User')%>[], number]> { <%_ if (databaseType !== 'mongodb') { _%> options.relations = ['authorities']; <%_ } _%> const resultList = await this.userRepository.findAndCount(options); - const usersDTO: UserDTO[] = []; + const usersDTO: <%= asDto('User')%>[] = []; if (resultList && resultList[0]) { resultList[0].forEach(user => usersDTO.push(UserMapper.fromEntityToDTO(this.flatAuthorities(user)))); resultList[0] = usersDTO; @@ -42,7 +42,7 @@ export class UserService { return resultList; } - async save(userDTO: UserDTO, creator?: string, updatePassword = false): Promise { + async save(userDTO: <%= asDto('User')%>, creator?: string, updatePassword = false): Promise<<%= asDto('User')%> | undefined> { const user = this.convertInAuthorities(UserMapper.fromDTOtoEntity(userDTO)); if (updatePassword) { await transformPassword(user); @@ -57,17 +57,17 @@ export class UserService { return UserMapper.fromEntityToDTO(this.flatAuthorities(result)); } - async update(userDTO: UserDTO, updater?: string): Promise { + async update(userDTO: <%= asDto('User')%>, updater?: string): Promise<<%= asDto('User')%> | undefined> { return this.save(userDTO, updater); } - async delete(userDTO: UserDTO): Promise { + async delete(userDTO: <%= asDto('User')%>): Promise<<%= asDto('User')%> | undefined> { const user = UserMapper.fromDTOtoEntity(userDTO); const result = await this.userRepository.remove(user) return UserMapper.fromEntityToDTO(result); } - private flatAuthorities(user: any): User { + private flatAuthorities(user: any): <%= asEntity('User') %> { if (user && user.authorities) { const authorities: string[] = []; user.authorities.forEach(authority => authorities.push(authority.name)); @@ -76,7 +76,7 @@ export class UserService { return user; } - private convertInAuthorities(user: any): User { + private convertInAuthorities(user: any): <%= asEntity('User') %> { if (user && user.authorities) { const authorities: any[] = []; user.authorities.forEach(authority => authorities.push({ name: authority })); diff --git a/generators/server/templates/server/src/web/rest/account.controller.ts.ejs b/generators/server/templates/server/src/web/rest/account.controller.ts.ejs index bdbbcc5d..90e1b5ef 100644 --- a/generators/server/templates/server/src/web/rest/account.controller.ts.ejs +++ b/generators/server/templates/server/src/web/rest/account.controller.ts.ejs @@ -5,7 +5,7 @@ import { Response, Request } from 'express'; import { AuthGuard, Roles, RoleType, RolesGuard } from '../../security'; import { PasswordChangeDTO } from '../../service/dto/password-change.dto'; <%_ } _%> -import { UserDTO } from '../../service/dto/user.dto'; +import { <%= asDto('User')%> } from '../../service/dto/user.dto'; import { LoggingInterceptor } from '../../client/interceptors/logging.interceptor'; import {<%_ if (authenticationType === 'jwt') { _%> ApiBearerAuth, <%_ } _%> ApiUseTags, ApiResponse, ApiOperation } from '@nestjs/swagger'; import { AuthService } from '../../service/auth.service'; @@ -24,9 +24,9 @@ export class AccountController { @ApiResponse({ status: 201, description: 'Registered user', - type: UserDTO, + type: <%= asDto('User')%>, }) - async registerAccount(@Req() req: Request, @Body() userDTO: UserDTO & { password: string }): Promise { + async registerAccount(@Req() req: Request, @Body() userDTO: <%= asDto('User')%> & { password: string }): Promise { return await this.authService.registerNewUser(userDTO); } @@ -85,9 +85,9 @@ export class AccountController { @ApiResponse({ status: 201, description: 'user info updated', - type: UserDTO, + type: <%= asDto('User')%>, }) - async saveAccount(@Req() req: Request, @Body() newUserInfo: UserDTO): Promise { + async saveAccount(@Req() req: Request, @Body() newUserInfo: <%= asDto('User')%>): Promise { const user: any = req.user; return await this.authService.updateUserSettings(user.login, newUserInfo); } @@ -139,13 +139,13 @@ export class AccountController { @ApiResponse({ status: 200, description: 'User retrieved', - type: UserDTO, + type: <%= asDto('User')%>, }) getAccount(@Req() req: any): any { if(!req.session) { return; } - const userDTO: UserDTO = req.session.user; + const userDTO: <%= asDto('User')%> = req.session.user; return this.authService.getAccount(userDTO); } diff --git a/generators/server/templates/server/src/web/rest/public.user.controller.ts.ejs b/generators/server/templates/server/src/web/rest/public.user.controller.ts.ejs index 93235929..b979ad9c 100644 --- a/generators/server/templates/server/src/web/rest/public.user.controller.ts.ejs +++ b/generators/server/templates/server/src/web/rest/public.user.controller.ts.ejs @@ -1,7 +1,7 @@ import { Controller, ClassSerializerInterceptor, Get, Logger, Req, UseInterceptors } from '@nestjs/common'; import { LoggingInterceptor } from '../../client/interceptors/logging.interceptor'; import { PageRequest, Page } from '../../domain/base/pagination.entity'; -import { UserDTO } from '../../service/dto/user.dto'; +import { <%= asDto('User')%> } from '../../service/dto/user.dto'; import { Request } from 'express'; import { HeaderUtil } from '../../client/header-util'; import { ApiUseTags, ApiResponse, ApiOperation } from '@nestjs/swagger'; @@ -21,9 +21,9 @@ export class PublicUserController { @ApiResponse({ status: 200, description: 'List all users records', - type: UserDTO, + type: <%= asDto('User')%>, }) - async getAllPublicUsers(@Req() req: Request): Promise { + async getAllPublicUsers(@Req() req: Request): Promise<<%= asDto('User')%>[]> { <%_ if (databaseType === 'mongodb') { _%> const sortField = ''; <%_ } else { _%> diff --git a/generators/server/templates/server/src/web/rest/user.controller.ts.ejs b/generators/server/templates/server/src/web/rest/user.controller.ts.ejs index c70c6d67..2a7866ea 100644 --- a/generators/server/templates/server/src/web/rest/user.controller.ts.ejs +++ b/generators/server/templates/server/src/web/rest/user.controller.ts.ejs @@ -1,7 +1,7 @@ import { Body, Controller, Delete, Get, Logger, Param, Post, Put, UseGuards, Req, UseInterceptors, ClassSerializerInterceptor } from '@nestjs/common'; import { AuthGuard, Roles, RolesGuard, RoleType } from '../../security'; import { PageRequest, Page } from '../../domain/base/pagination.entity'; -import { UserDTO } from '../../service/dto/user.dto'; +import { <%= asDto('User')%> } from '../../service/dto/user.dto'; import { HeaderUtil } from '../../client/header-util'; import { Request } from '../../client/request'; import { LoggingInterceptor } from '../../client/interceptors/logging.interceptor'; @@ -28,9 +28,9 @@ export class UserController { @ApiResponse({ status: 200, description: 'List all users', - type: UserDTO, + type: <%= asDto('User')%>, }) - async getAllUsers(@Req() req: Request): Promise { + async getAllUsers(@Req() req: Request): Promise<<%= asDto('User')%>[]> { <%_ if (databaseType === 'mongodb') { _%> const sortField = ''; <%_ } else { _%> @@ -52,10 +52,10 @@ export class UserController { @ApiResponse({ status: 201, description: 'The record has been successfully created.', - type: UserDTO, + type: <%= asDto('User')%>, }) @ApiResponse({ status: 403, description: 'Forbidden.' }) - async createUser(@Req() req: Request, @Body() userDTO: UserDTO): Promise { + async createUser(@Req() req: Request, @Body() userDTO: <%= asDto('User')%>): Promise<<%= asDto('User')%>> { userDTO.password = userDTO.login; const created = await this.userService.save(userDTO, req.user?.login); HeaderUtil.addEntityCreatedHeaders(req.res, 'User', created.id); @@ -68,9 +68,9 @@ export class UserController { @ApiResponse({ status: 200, description: 'The record has been successfully updated.', - type: UserDTO, + type: <%= asDto('User')%>, }) - async updateUser(@Req() req: Request, @Body() userDTO: UserDTO): Promise { + async updateUser(@Req() req: Request, @Body() userDTO: <%= asDto('User')%>): Promise<<%= asDto('User')%>> { const userOnDb = await this.userService.find({ where: { login: userDTO.login } }); let updated = false; if (userOnDb && userOnDb.id) { @@ -94,9 +94,9 @@ export class UserController { @ApiResponse({ status: 200, description: 'The found record', - type: UserDTO, + type: <%= asDto('User')%>, }) - async getUser(@Param('login') loginValue: string): Promise { + async getUser(@Param('login') loginValue: string): Promise<<%= asDto('User')%>> { return await this.userService.find({ where: { login: loginValue } }); } @@ -106,9 +106,9 @@ export class UserController { @ApiResponse({ status: 204, description: 'The record has been successfully deleted.', - type: UserDTO + type: <%= asDto('User')%> }) - async deleteUser(@Req() req: Request, @Param('login') loginValue: string): Promise { + async deleteUser(@Req() req: Request, @Param('login') loginValue: string): Promise<<%= asDto('User')%>> { HeaderUtil.addEntityDeletedHeaders(req.res, 'User', loginValue); const userToDelete = await this.userService.find({ where: { login: loginValue } }); return await this.userService.delete(userToDelete);