From c6cf8b01206857440395897a3381b63cb8e2d709 Mon Sep 17 00:00:00 2001 From: Markus Glutting Date: Mon, 7 Jun 2021 14:11:29 +0200 Subject: [PATCH] Automatically set createdBy, createdDate, lastModifiedBy and lastModifiedDate closes #236 --- .../server/src/service/entity.service.ts.ejs | 17 +++++++++++++---- .../server/e2e/account.e2e-spec.ts.ejs | 2 +- .../server/src/domain/base/base.entity.ts.ejs | 6 +++--- .../server/src/service/auth.service.ts.ejs | 14 +++++++------- .../server/src/service/user.service.ts.ejs | 16 ++++++++++++---- 5 files changed, 36 insertions(+), 19 deletions(-) diff --git a/generators/entity-server/templates/server/src/service/entity.service.ts.ejs b/generators/entity-server/templates/server/src/service/entity.service.ts.ejs index acfd87010..3b1cf6b51 100644 --- a/generators/entity-server/templates/server/src/service/entity.service.ts.ejs +++ b/generators/entity-server/templates/server/src/service/entity.service.ts.ejs @@ -1,6 +1,9 @@ -import { Injectable, HttpException, HttpStatus, Logger } from '@nestjs/common'; +import { Injectable, HttpException, HttpStatus, Logger, Scope, Inject } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { FindManyOptions, FindOneOptions } from 'typeorm'; +import { REQUEST } from '@nestjs/core'; +import { Request } from 'express'; +import { UserDTO } from './dto/user.dto'; import { <%= entityClass %>DTO } from '../service/dto/<%= entityFileName %>.dto'; import { <%= entityClass %>Mapper } from '../service/mapper/<%= entityFileName %>.mapper'; import { <%= entityClass %>Repository } from '../repository/<%= entityFileName %>.repository'; @@ -22,11 +25,12 @@ for (idx in relationships) { } _%> -@Injectable() +@Injectable({ scope: Scope.REQUEST }) export class <%= entityClass %>Service { logger = new Logger('<%= entityClass %>Service'); - constructor(@InjectRepository(<%= entityClass %>Repository) private <%= asEntity(entityInstance) %>Repository: <%= entityClass %>Repository) {} + constructor(@InjectRepository(<%= entityClass %>Repository) private <%= asEntity(entityInstance) %>Repository: <%= entityClass %>Repository, + @Inject(REQUEST) private readonly request: Request) {} async findById(id: string): Promise<<%= entityClass %>DTO | undefined> { const options = { relations: relationshipNames }; @@ -34,7 +38,7 @@ export class <%= entityClass %>Service { return <%= entityClass %>Mapper.fromEntityToDTO(result); } - async findByfields(options: FindOneOptions<<%= entityClass %>DTO>): Promise<<%= entityClass %>DTO | undefined> { + async findByFields(options: FindOneOptions<<%= entityClass %>DTO>): Promise<<%= entityClass %>DTO | undefined> { const result = await this.<%= asEntity(entityInstance) %>Repository.findOne(options); return <%= entityClass %>Mapper.fromEntityToDTO(result); } @@ -52,12 +56,17 @@ export class <%= entityClass %>Service { async save(<%= asEntity(entityInstance) %>DTO: <%= entityClass %>DTO): Promise<<%= entityClass %>DTO | undefined> { const entity = <%= entityClass %>Mapper.fromDTOtoEntity(<%= asEntity(entityInstance) %>DTO); + if (!entity.createdBy) { + entity.createdBy = (this.request.user as UserDTO).login; + } + entity.lastModifiedBy = (this.request.user as UserDTO).login; const result = await this.<%= asEntity(entityInstance) %>Repository.save(entity); return <%= entityClass %>Mapper.fromEntityToDTO(result); } async update(<%= asEntity(entityInstance) %>DTO: <%= entityClass %>DTO): Promise<<%= entityClass %>DTO | undefined> { const entity = <%= entityClass %>Mapper.fromDTOtoEntity(<%= asEntity(entityInstance) %>DTO); + entity.lastModifiedBy = (this.request.user as UserDTO).login; <%_ if (databaseType === 'mongodb') { _%> await this.<%= asEntity(entityInstance) %>Repository.update(entity.id, entity); return <%= asEntity(entityInstance) %>DTO; 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 1f00db8fe..1845dc86d 100644 --- a/generators/server/templates/server/e2e/account.e2e-spec.ts.ejs +++ b/generators/server/templates/server/e2e/account.e2e-spec.ts.ejs @@ -119,7 +119,7 @@ describe('Account', () => { .send(savedTestUser) .expect(201); - const updatedUserSettings: UserDTO = await service.findByfields({ where: { login: testUserAuthenticated.login } }); + const updatedUserSettings: UserDTO = 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/src/domain/base/base.entity.ts.ejs b/generators/server/templates/server/src/domain/base/base.entity.ts.ejs index 295125d24..e72baf245 100644 --- a/generators/server/templates/server/src/domain/base/base.entity.ts.ejs +++ b/generators/server/templates/server/src/domain/base/base.entity.ts.ejs @@ -1,4 +1,4 @@ -import { <%_ if (databaseType === 'mongodb') { _%> ObjectIdColumn <%_ } else { _%> PrimaryGeneratedColumn <%_ } _%>, Column } from 'typeorm'; +import { <%_ if (databaseType === 'mongodb') { _%> ObjectIdColumn <%_ } else { _%> PrimaryGeneratedColumn <%_ } _%>, Column, CreateDateColumn, UpdateDateColumn } from 'typeorm'; export abstract class BaseEntity { @@ -15,11 +15,11 @@ export abstract class BaseEntity { @Column({ nullable: true }) createdBy?: string; - @Column({ nullable: true }) + @CreateDateColumn({ nullable: true }) createdDate?: Date; @Column({ nullable: true }) lastModifiedBy?: string; - @Column({ nullable: true }) + @UpdateDateColumn({ nullable: true }) lastModifiedDate?: Date; 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 6ca5edc42..ee867d113 100644 --- a/generators/server/templates/server/src/service/auth.service.ts.ejs +++ b/generators/server/templates/server/src/service/auth.service.ts.ejs @@ -59,7 +59,7 @@ export class AuthService { <%_ if (databaseType === 'mongodb') { _%> const userDTO: UserDTO = await this.userService.findById(userId); <%_ } else { _%> - const userDTO: UserDTO = await this.userService.findByfields({ where: { id: userId } }); + const userDTO: UserDTO = await this.userService.findByFields({ where: { id: userId } }); <%_ } _%> return userDTO; } @@ -73,7 +73,7 @@ export class AuthService { } async changePassword(userLogin: string, currentClearTextPassword: string, newPassword: string): Promise { - const userFind: UserDTO = await this.userService.findByfields({ where: { login: userLogin }, select: [ 'id', 'password' ] }); + const userFind: UserDTO = await this.userService.findByFields({ where: { login: userLogin }, select: [ 'id', 'password' ] }); if (!userFind) { throw new HttpException('Invalid login name!', HttpStatus.BAD_REQUEST); } @@ -86,11 +86,11 @@ export class AuthService { } async registerNewUser (newUser: UserDTO) : Promise { - let userFind: UserDTO = await this.userService.findByfields({ where: { login: newUser.login} }); + let userFind: UserDTO = await this.userService.findByFields({ where: { login: newUser.login} }); if (userFind) { throw new HttpException('Login name already used!', HttpStatus.BAD_REQUEST); } - userFind = await this.userService.findByfields({ where: { email: newUser.email} }); + userFind = await this.userService.findByFields({ where: { email: newUser.email} }); if (userFind) { throw new HttpException('Email is already in use!', HttpStatus.BAD_REQUEST); } @@ -100,11 +100,11 @@ export class AuthService { } async updateUserSettings(userLogin: string, newUserInfo: UserDTO) : Promise { - const userFind: UserDTO = await this.userService.findByfields({ where: { login: userLogin } }); + const userFind: UserDTO = 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: UserDTO = 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); } @@ -122,7 +122,7 @@ export class AuthService { 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: UserDTO = await this.userService.findByFields({ where: { login: loginUser.login } }); if (!userFound) { const authoritiesName = []; 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 680b2eb78..9451039fd 100644 --- a/generators/server/templates/server/src/service/user.service.ts.ejs +++ b/generators/server/templates/server/src/service/user.service.ts.ejs @@ -1,21 +1,24 @@ -import { Injectable } from '@nestjs/common'; +import { Injectable, Scope, Inject } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { User } from '../domain/user.entity'; import { UserDTO } from './dto/user.dto'; import { UserMapper } from './mapper/user.mapper'; import { UserRepository } from '../repository/user.repository'; import { FindManyOptions, FindOneOptions } from 'typeorm'; +import { REQUEST } from '@nestjs/core'; +import { Request } from 'express'; -@Injectable() +@Injectable({ scope: Scope.REQUEST }) export class UserService { - constructor(@InjectRepository(UserRepository) private userRepository: UserRepository) {} + constructor(@InjectRepository(UserRepository) private userRepository: UserRepository, + @Inject(REQUEST) private readonly request: Request) {} async findById(id: <%= getPkType(databaseType) === 'Long' ? 'number' : 'string' %>): Promise { const result = await this.userRepository.findOne(id); return UserMapper.fromEntityToDTO(this.flatAuthorities(result)) } - async findByfields(options: FindOneOptions): Promise { + async findByFields(options: FindOneOptions): Promise { <%_ if (databaseType !== 'mongodb') { _%> options.relations = ['authorities']; <%_ } _%> @@ -43,12 +46,17 @@ export class UserService { async save(userDTO: UserDTO): Promise { const user = this.convertInAuthorities(UserMapper.fromDTOtoEntity(userDTO)); + if (!user.createdBy) { + user.createdBy = (this.request.user as UserDTO).login; + } + user.lastModifiedBy = (this.request.user as UserDTO).login; const result = await this.userRepository.save(user); return UserMapper.fromEntityToDTO(this.flatAuthorities(result)); } async update(userDTO: UserDTO): Promise { const user = await this.save(UserMapper.fromDTOtoEntity(userDTO)); + user.lastModifiedBy = (this.request.user as UserDTO).login; return UserMapper.fromEntityToDTO(user); }