Skip to content

Commit

Permalink
Automatically set createdBy, createdDate, lastModifiedBy and lastModi…
Browse files Browse the repository at this point in the history
…fiedDate closes jhipster#236
  • Loading branch information
glutengo committed Jun 7, 2021
1 parent 139a71b commit ae8572b
Show file tree
Hide file tree
Showing 9 changed files with 45 additions and 20 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { Injectable, HttpException, HttpStatus, Logger } from '@nestjs/common';
import { Injectable, HttpException, HttpStatus, Logger, Inject } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { FindManyOptions, FindOneOptions } from 'typeorm';
import { REQUEST } from '@nestjs/core';
import { Request } from '../security';
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';
Expand All @@ -26,15 +29,16 @@ _%>
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 };
const result = await this.<%= asEntity(entityInstance) %>Repository.findOne(id, options);
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);
}
Expand All @@ -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.login;
}
entity.lastModifiedBy = this.request.user.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.login;
<%_ if (databaseType === 'mongodb') { _%>
await this.<%= asEntity(entityInstance) %>Repository.update(entity.id, entity);
return <%= asEntity(entityInstance) %>DTO;
Expand Down
1 change: 1 addition & 0 deletions generators/server/files.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ const serverFiles = {
'src/security/role-type.ts',
'src/security/decorators/auth-user.decorator.ts',
'src/security/decorators/roles.decorator.ts',
'src/security/request.ts',
'src/security/index.ts',
'src/client/header-util.ts',
'src/client/interceptors/logging.interceptor.ts',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down
4 changes: 2 additions & 2 deletions generators/server/templates/server/e2e/user.e2e-spec.ts.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ describe('User', () => {
).body;

<%_ if (databaseType !== 'mongodb') { _%>
expect(updatedUser).toEqual(savedUser);
expect(updatedUser).toEqual(JSON.parse(JSON.stringify(savedUser)));
<%_ } else { _%>
expect(updatedUser.firstName).toEqual(savedUser.firstName);
<%_ } _%>
Expand All @@ -96,7 +96,7 @@ describe('User', () => {
).body;

<%_ if (databaseType !== 'mongodb') { _%>
expect(getUser).toEqual(savedUserWithoutPassword);
expect(getUser).toEqual(JSON.parse(JSON.stringify(savedUserWithoutPassword)));
<%_ } else { _%>
expect(getUser.login).toEqual(savedUser.login);
<%_ } _%>
Expand Down
Original file line number Diff line number Diff line change
@@ -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 {

Expand All @@ -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;


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ export * from './guards/roles.guard';
export * from './decorators/roles.decorator';
export * from './decorators/auth-user.decorator';
export * from './role-type';
export * from './request';
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { Request as ExpressRequest} from 'express';
import { UserDTO } from '../service/dto/user.dto';

export interface Request extends ExpressRequest {
user: UserDTO;
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export class AuthService {
const loginUserName = userLogin.username;
const loginPassword = userLogin.password;
const userFind = await this.userService.findByfields({ where: { login: loginUserName, password: loginPassword } });
const userFind = await this.userService.findByFields({ where: { login: loginUserName, password: loginPassword } });
if (!userFind) {
throw new HttpException('Invalid login name or password!', HttpStatus.BAD_REQUEST);
}
Expand Down Expand Up @@ -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;
}
Expand All @@ -73,7 +73,7 @@ export class AuthService {
}
async changePassword(userLogin: string, currentClearTextPassword: string, newPassword: string): Promise<void> {
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);
}
Expand All @@ -86,11 +86,11 @@ export class AuthService {
}
async registerNewUser (newUser: UserDTO) : Promise<UserDTO> {
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);
}
Expand All @@ -100,11 +100,11 @@ export class AuthService {
}
async updateUserSettings(userLogin: string, newUserInfo: UserDTO) : Promise<UserDTO> {
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);
}
Expand All @@ -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 = [];
Expand Down
14 changes: 11 additions & 3 deletions generators/server/templates/server/src/service/user.service.ts.ejs
Original file line number Diff line number Diff line change
@@ -1,21 +1,24 @@
import { Injectable } from '@nestjs/common';
import { Injectable, 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 '../security'

@Injectable()
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<UserDTO | undefined> {
const result = await this.userRepository.findOne(id);
return UserMapper.fromEntityToDTO(this.flatAuthorities(result))
}

async findByfields(options: FindOneOptions<UserDTO>): Promise<UserDTO | undefined> {
async findByFields(options: FindOneOptions<UserDTO>): Promise<UserDTO | undefined> {
<%_ if (databaseType !== 'mongodb') { _%>
options.relations = ['authorities'];
<%_ } _%>
Expand Down Expand Up @@ -43,12 +46,17 @@ export class UserService {

async save(userDTO: UserDTO): Promise<UserDTO | undefined> {
const user = this.convertInAuthorities(UserMapper.fromDTOtoEntity(userDTO));
if (!user.createdBy) {
user.createdBy = this.request.user.login;
}
user.lastModifiedBy = this.request.user.login;
const result = await this.userRepository.save(user);
return UserMapper.fromEntityToDTO(this.flatAuthorities(result));
}

async update(userDTO: UserDTO): Promise<UserDTO | undefined> {
const user = await this.save(UserMapper.fromDTOtoEntity(userDTO));
user.lastModifiedBy = this.request.user.login;
return UserMapper.fromEntityToDTO(user);
}

Expand Down

0 comments on commit ae8572b

Please sign in to comment.