Skip to content

Commit

Permalink
Adjust method signature instead of injecting request
Browse files Browse the repository at this point in the history
  • Loading branch information
glutengo committed Jun 8, 2021
1 parent 70c29fd commit 4419d1b
Show file tree
Hide file tree
Showing 8 changed files with 40 additions and 45 deletions.
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
import { HttpException, HttpStatus, Inject, Injectable, Logger, Scope } from '@nestjs/common';
import { Injectable, HttpException, HttpStatus, Logger } 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 @@ -25,12 +22,11 @@ for (idx in relationships) {
}
_%>

@Injectable({ scope: Scope.REQUEST })
@Injectable()
export class <%= entityClass %>Service {
logger = new Logger('<%= entityClass %>Service');

constructor(@InjectRepository(<%= entityClass %>Repository) private <%= asEntity(entityInstance) %>Repository: <%= entityClass %>Repository,
@Inject(REQUEST) private readonly request: Request) {}
constructor(@InjectRepository(<%= entityClass %>Repository) private <%= asEntity(entityInstance) %>Repository: <%= entityClass %>Repository) {}

async findById(id: string): Promise<<%= entityClass %>DTO | undefined> {
const options = { relations: relationshipNames };
Expand All @@ -54,19 +50,23 @@ export class <%= entityClass %>Service {
return resultList;
}

async save(<%= asEntity(entityInstance) %>DTO: <%= entityClass %>DTO): Promise<<%= entityClass %>DTO | undefined> {
async save(<%= asEntity(entityInstance) %>DTO: <%= entityClass %>DTO, creator?: string): Promise<<%= entityClass %>DTO | undefined> {
const entity = <%= entityClass %>Mapper.fromDTOtoEntity(<%= asEntity(entityInstance) %>DTO);
if (!entity.createdBy) {
entity.createdBy = this.request?.user?.login || null;
if (creator) {
if (!entity.createdBy) {
entity.createdBy = creator;
}
entity.lastModifiedBy = creator;
}
entity.lastModifiedBy = this.request?.user?.login || null;
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> {
async update(<%= asEntity(entityInstance) %>DTO: <%= entityClass %>DTO, updater?: string): Promise<<%= entityClass %>DTO | undefined> {
const entity = <%= entityClass %>Mapper.fromDTOtoEntity(<%= asEntity(entityInstance) %>DTO);
entity.lastModifiedBy = this.request?.user?.login || null;
if (updater) {
entity.lastModifiedBy = updater;
}
<%_ if (databaseType === 'mongodb') { _%>
await this.<%= asEntity(entityInstance) %>Repository.update(entity.id, entity);
return <%= asEntity(entityInstance) %>DTO;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import { Body, Controller, Delete, Get, Logger, Param, Post as PostMethod, Put, UseGuards, Req, UseInterceptors } from '@nestjs/common';
import { <% if (authenticationType === 'jwt') { _%> ApiBearerAuth, <% } else if (authenticationType === 'oauth2') { _%> ApiOAuth2Auth, <% } _%> ApiUseTags, ApiResponse, ApiOperation } from '@nestjs/swagger';
import { Request } from 'express';
import { <%= entityClass %>DTO } from '../../service/dto/<%= entityFileName %>.dto';
import { <%= entityClass %>Service } from '../../service/<%= entityFileName %>.service';
import { PageRequest, Page } from '../../domain/base/pagination.entity';
import { AuthGuard, Roles, RolesGuard, RoleType } from '../../security';
import { AuthGuard, Request, Roles, RolesGuard, RoleType } from '../../security';
import { HeaderUtil } from '../../client/header-util';
import { LoggingInterceptor } from '../../client/interceptors/logging.interceptor';

Expand Down Expand Up @@ -62,7 +61,7 @@ export class <%= entityClass %>Controller {
})
@ApiResponse({ status: 403, description: 'Forbidden.' })
async post(@Req() req: Request, @Body() <%= asEntity(entityInstance) %>DTO: <%= entityClass %>DTO): Promise<<%= entityClass %>DTO> {
const created = await this.<%= asEntity(entityInstance) %>Service.save(<%= asEntity(entityInstance) %>DTO);
const created = await this.<%= asEntity(entityInstance) %>Service.save(<%= asEntity(entityInstance) %>DTO, req.user?.login);
HeaderUtil.addEntityCreatedHeaders(req.res, '<%= entityClass %>', created.id);
return created;
}
Expand All @@ -77,7 +76,7 @@ export class <%= entityClass %>Controller {
})
async put(@Req() req: Request, @Body() <%= asEntity(entityInstance) %>DTO: <%= entityClass %>DTO): Promise<<%= entityClass %>DTO> {
HeaderUtil.addEntityCreatedHeaders(req.res, '<%= entityClass %>', <%= asEntity(entityInstance) %>DTO.id);
return await this.<%= asEntity(entityInstance) %>Service.update(<%= asEntity(entityInstance) %>DTO);
return await this.<%= asEntity(entityInstance) %>Service.update(<%= asEntity(entityInstance) %>DTO, req.user?.login);
}

@Put('/:id')
Expand All @@ -90,7 +89,7 @@ export class <%= entityClass %>Controller {
})
async putId(@Req() req: Request, @Body() <%= asEntity(entityInstance) %>DTO: <%= entityClass %>DTO): Promise<<%= entityClass %>DTO> {
HeaderUtil.addEntityCreatedHeaders(req.res, '<%= entityClass %>', <%= asEntity(entityInstance) %>DTO.id);
return await this.<%= asEntity(entityInstance) %>Service.update(<%= asEntity(entityInstance) %>DTO);
return await this.<%= asEntity(entityInstance) %>Service.update(<%= asEntity(entityInstance) %>DTO, req.user?.login);
}

@Delete('/:id')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,9 @@ describe('Account', () => {

app = moduleFixture.createNestApplication();
await app.init();
service = await moduleFixture.resolve<UserService>(UserService);
authService = await moduleFixture.resolve<AuthService>(AuthService);
userAuthenticated = await service.save(testUserAuthenticated, true);
service = moduleFixture.get<UserService>(UserService);
authService = moduleFixture.get<AuthService>(AuthService);
userAuthenticated = await service.save(testUserAuthenticated, testUserAuthenticated.login, true);
});

it('/POST register new user', async () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ describe('User', () => {

app = moduleFixture.createNestApplication();
await app.init();
service = await moduleFixture.resolve<UserService>(UserService);
service = moduleFixture.get<UserService>(UserService);
});

it('/POST create user', async () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@ import { Request as ExpressRequest} from 'express';
import { UserDTO } from '../service/dto/user.dto';

export interface Request extends ExpressRequest {
user: UserDTO;
user?: UserDTO;
}
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ export class AuthService {
throw new HttpException('Invalid password!', HttpStatus.BAD_REQUEST);
}
userFind.password = newPassword;
await this.userService.save(userFind, true);
await this.userService.save(userFind, userLogin, true);
return;
}
Expand All @@ -98,7 +98,7 @@ 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, true);
const user: UserDTO = await this.userService.save(newUser, newUser.login, true);
return user;
}
Expand All @@ -116,7 +116,7 @@ export class AuthService {
userFind.lastName = newUserInfo.lastName;
userFind.email = newUserInfo.email;
userFind.langKey = newUserInfo.langKey;
await this.userService.save(userFind);
await this.userService.save(userFind, userLogin);
return;
}
Expand All @@ -132,7 +132,7 @@ export class AuthService {
loginUser.authorities.forEach(authority => authoritiesName.push({ name: authority }));
userFound = Object.assign({}, loginUser);
userFound.authorities = authoritiesName;
await this.userService.save(userFound);
await this.userService.save(userFound, loginUser.login);
}
return loginUser;
}
Expand Down
25 changes: 11 additions & 14 deletions generators/server/templates/server/src/service/user.service.ts.ejs
Original file line number Diff line number Diff line change
@@ -1,18 +1,15 @@
import { Injectable, Inject, Scope } from '@nestjs/common';
import { Injectable } 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 { transformPassword } from '../security';
import { REQUEST } from '@nestjs/core';
import { Request } from '../security'

@Injectable({ scope: Scope.REQUEST })
@Injectable()
export class UserService {
constructor(@InjectRepository(UserRepository) private userRepository: UserRepository,
@Inject(REQUEST) private readonly request: Request) {}
constructor(@InjectRepository(UserRepository) private userRepository: UserRepository) {}

async findById(id: <%= getPkType(databaseType) === 'Long' ? 'number' : 'string' %>): Promise<UserDTO | undefined> {
const result = await this.userRepository.findOne(id);
Expand Down Expand Up @@ -45,23 +42,23 @@ export class UserService {
return resultList;
}

async save(userDTO: UserDTO, updatePassword = false): Promise<UserDTO | undefined> {
async save(userDTO: UserDTO, creator?: string, updatePassword = false): Promise<UserDTO | undefined> {
const user = this.convertInAuthorities(UserMapper.fromDTOtoEntity(userDTO));
if (updatePassword) {
await transformPassword(user);
}
if (!user.createdBy) {
user.createdBy = this.request?.user?.login || null;
if (creator) {
if (!user.createdBy ) {
user.createdBy = creator;
}
user.lastModifiedBy = creator;
}
user.lastModifiedBy = this.request?.user?.login || null;
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 || null;
return UserMapper.fromEntityToDTO(user);
async update(userDTO: UserDTO, updater?: string): Promise<UserDTO | undefined> {
return this.save(userDTO, updater);
}

async delete(userDTO: UserDTO): Promise<UserDTO | undefined> {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { Body, Controller, Delete, Get, Logger, Param, Post, Put, UseGuards, Req, UseInterceptors, ClassSerializerInterceptor } from '@nestjs/common';
import { Request } from 'express';
import { AuthGuard, Roles, RolesGuard, RoleType } from '../../security';
import { AuthGuard, Request, Roles, RolesGuard, RoleType } from '../../security';
import { PageRequest, Page } from '../../domain/base/pagination.entity';
import { UserDTO } from '../../service/dto/user.dto';
import { HeaderUtil } from '../../client/header-util';
Expand Down Expand Up @@ -57,7 +56,7 @@ export class UserController {
@ApiResponse({ status: 403, description: 'Forbidden.' })
async createUser(@Req() req: Request, @Body() userDTO: UserDTO): Promise<UserDTO> {
userDTO.password = userDTO.login;
const created = await this.userService.save(userDTO);
const created = await this.userService.save(userDTO, req.user?.login);
HeaderUtil.addEntityCreatedHeaders(req.res, 'User', created.id);
return created;
}
Expand All @@ -79,7 +78,7 @@ export class UserController {
} else {
userDTO.password = userDTO.login;
}
const createdOrUpdated = await this.userService.update(userDTO);
const createdOrUpdated = await this.userService.update(userDTO, req.user?.login);
if (updated) {
HeaderUtil.addEntityUpdatedHeaders(req.res, 'User', createdOrUpdated.id);
} else {
Expand Down

0 comments on commit 4419d1b

Please sign in to comment.