diff --git a/src/app.module.ts b/src/app.module.ts index 5987541..6e0e7bf 100644 --- a/src/app.module.ts +++ b/src/app.module.ts @@ -1,5 +1,5 @@ import { Module } from '@nestjs/common'; -import { ConfigModule, ConfigService } from '@nestjs/config' +import { ConfigModule, ConfigService } from '@nestjs/config'; import { TypeOrmModule } from '@nestjs/typeorm'; import { AccessControlModule } from 'nest-access-control'; @@ -8,7 +8,13 @@ import { AppService } from './app.service'; import { PostModule } from './post/post.module'; import { UserModule } from './user/user.module'; import { AuthModule } from './auth/auth.module'; -import { DATABASE_HOST, DATABASE_PORT, DATABASE_USERNAME, DATABASE_PASSWORD, DATABASE_NAME } from './config/constants'; +import { + DATABASE_HOST, + DATABASE_PORT, + DATABASE_USERNAME, + DATABASE_PASSWORD, + DATABASE_NAME, +} from './config/constants'; import { roles } from './app.roles'; @Module({ @@ -27,11 +33,11 @@ import { roles } from './app.roles'; synchronize: true, logging: true, logger: 'file', - }) + }), }), ConfigModule.forRoot({ isGlobal: true, - envFilePath: '.env' + envFilePath: '.env', }), AccessControlModule.forRoles(roles), AuthModule, diff --git a/src/app.roles.ts b/src/app.roles.ts index ec63e6a..14acac7 100644 --- a/src/app.roles.ts +++ b/src/app.roles.ts @@ -1,13 +1,13 @@ -import { RolesBuilder } from "nest-access-control"; +import { RolesBuilder } from 'nest-access-control'; export enum AppRoles { AUTHOR = 'AUTHOR', - ADMIN = 'ADMIN' + ADMIN = 'ADMIN', } export enum AppResource { USER = 'USER', - POST = 'POST' + POST = 'POST', } export const roles: RolesBuilder = new RolesBuilder(); @@ -25,5 +25,4 @@ roles .extend(AppRoles.AUTHOR) .createAny([AppResource.USER]) .updateAny([AppResource.POST, AppResource.USER]) - .deleteAny([AppResource.POST, AppResource.USER]) - + .deleteAny([AppResource.POST, AppResource.USER]); diff --git a/src/auth/auth.controller.ts b/src/auth/auth.controller.ts index cf43044..4c0279f 100644 --- a/src/auth/auth.controller.ts +++ b/src/auth/auth.controller.ts @@ -9,45 +9,34 @@ import { LoginDto } from './dtos/login.dto'; @ApiTags('Auth routes') @Controller('auth') export class AuthController { - - constructor( - private readonly authService: AuthService - ) {} + constructor(private readonly authService: AuthService) {} @UseGuards(LocalAuthGuard) @Post('login') - async login( - @Body() loginDto: LoginDto, - @User() user: UserEntity - ) { + async login(@Body() loginDto: LoginDto, @User() user: UserEntity) { const data = await this.authService.login(user); return { message: 'Login exitoso', - data - } + data, + }; } @Auth() @Get('profile') - profile( - @User() user: UserEntity - ) { + profile(@User() user: UserEntity) { return { message: 'PeticiĆ³n correcta', - user - } + user, + }; } @Auth() @Get('refresh') - refreshToken( - @User() user: UserEntity - ) { + refreshToken(@User() user: UserEntity) { const data = this.authService.login(user); return { message: 'Refresh exitoso', - data - } + data, + }; } - } diff --git a/src/auth/auth.module.ts b/src/auth/auth.module.ts index a50ee1d..3195576 100644 --- a/src/auth/auth.module.ts +++ b/src/auth/auth.module.ts @@ -3,7 +3,7 @@ import { PassportModule } from '@nestjs/passport'; import { JwtModule } from '@nestjs/jwt'; import { ConfigService } from '@nestjs/config'; -import { JWT_SECRET } from '../config/constants' +import { JWT_SECRET } from '../config/constants'; import { AuthService } from './auth.service'; import { AuthController } from './auth.controller'; import { UserModule } from 'src/user/user.module'; @@ -12,16 +12,16 @@ import { LocalStrategy, JwtStrategy } from './strategies'; @Module({ imports: [ PassportModule.register({ - defaultStrategy: 'jwt' + defaultStrategy: 'jwt', }), JwtModule.registerAsync({ inject: [ConfigService], useFactory: (config: ConfigService) => ({ secret: config.get(JWT_SECRET), - signOptions: { expiresIn: '60m' } - }) + signOptions: { expiresIn: '60m' }, + }), }), - UserModule + UserModule, ], controllers: [AuthController], providers: [AuthService, LocalStrategy, JwtStrategy], diff --git a/src/auth/auth.service.ts b/src/auth/auth.service.ts index 7a4ecac..4749bd3 100644 --- a/src/auth/auth.service.ts +++ b/src/auth/auth.service.ts @@ -6,22 +6,20 @@ import { User } from 'src/user/entities'; @Injectable() export class AuthService { - constructor( private readonly userService: UserService, - private readonly jwtService: JwtService + private readonly jwtService: JwtService, ) {} async validateUser(email: string, pass: string): Promise { const user = await this.userService.findOne({ email }); - if(user && await compare(pass, user.password)) { + if (user && (await compare(pass, user.password))) { const { password, ...rest } = user; return rest; } return null; - } login(user: User) { @@ -30,7 +28,7 @@ export class AuthService { return { user, - accessToken: this.jwtService.sign(payload) - } + accessToken: this.jwtService.sign(payload), + }; } } diff --git a/src/auth/dtos/login.dto.ts b/src/auth/dtos/login.dto.ts index 7ca6973..41f4d84 100644 --- a/src/auth/dtos/login.dto.ts +++ b/src/auth/dtos/login.dto.ts @@ -1,6 +1,4 @@ - - export class LoginDto { email: string; password: string; -} \ No newline at end of file +} diff --git a/src/auth/guards/index.ts b/src/auth/guards/index.ts index 4f69f89..759d2eb 100644 --- a/src/auth/guards/index.ts +++ b/src/auth/guards/index.ts @@ -1,2 +1,2 @@ export * from './jwt-auth.guard'; -export * from './local-auth.guard'; \ No newline at end of file +export * from './local-auth.guard'; diff --git a/src/auth/guards/jwt-auth.guard.ts b/src/auth/guards/jwt-auth.guard.ts index abfeaaa..5f5d467 100644 --- a/src/auth/guards/jwt-auth.guard.ts +++ b/src/auth/guards/jwt-auth.guard.ts @@ -1,10 +1,8 @@ -import { Injectable, UnauthorizedException } from "@nestjs/common"; -import { AuthGuard } from "@nestjs/passport"; - +import { Injectable, UnauthorizedException } from '@nestjs/common'; +import { AuthGuard } from '@nestjs/passport'; @Injectable() export class JwtAuthGuard extends AuthGuard('jwt') { - handleRequest(err, user, info) { // You can throw an exception based on either "info" or "err" arguments if (err || !user) { @@ -12,4 +10,4 @@ export class JwtAuthGuard extends AuthGuard('jwt') { } return user; } -} \ No newline at end of file +} diff --git a/src/auth/guards/local-auth.guard.ts b/src/auth/guards/local-auth.guard.ts index bb6c34b..766f2f3 100644 --- a/src/auth/guards/local-auth.guard.ts +++ b/src/auth/guards/local-auth.guard.ts @@ -1,5 +1,5 @@ -import { AuthGuard } from "@nestjs/passport"; -import { Injectable } from "@nestjs/common"; +import { AuthGuard } from '@nestjs/passport'; +import { Injectable } from '@nestjs/common'; @Injectable() -export class LocalAuthGuard extends AuthGuard('local') {} \ No newline at end of file +export class LocalAuthGuard extends AuthGuard('local') {} diff --git a/src/auth/strategies/index.ts b/src/auth/strategies/index.ts index 8cc2485..e8ecb68 100644 --- a/src/auth/strategies/index.ts +++ b/src/auth/strategies/index.ts @@ -1,2 +1,2 @@ export * from './local.strategy'; -export * from './jwt.strategy'; \ No newline at end of file +export * from './jwt.strategy'; diff --git a/src/auth/strategies/jwt.strategy.ts b/src/auth/strategies/jwt.strategy.ts index 12bb5bd..324f808 100644 --- a/src/auth/strategies/jwt.strategy.ts +++ b/src/auth/strategies/jwt.strategy.ts @@ -7,10 +7,7 @@ import { JWT_SECRET } from 'src/config/constants'; @Injectable() export class JwtStrategy extends PassportStrategy(Strategy) { - constructor( - private userService: UserService, - private config: ConfigService, - ) { + constructor(private userService: UserService, private config: ConfigService) { super({ jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), ignoreExpiration: false, @@ -22,4 +19,4 @@ export class JwtStrategy extends PassportStrategy(Strategy) { const { sub: id } = payload; return await this.userService.getOne(id); } -} \ No newline at end of file +} diff --git a/src/auth/strategies/local.strategy.ts b/src/auth/strategies/local.strategy.ts index c5de382..44116eb 100644 --- a/src/auth/strategies/local.strategy.ts +++ b/src/auth/strategies/local.strategy.ts @@ -1,24 +1,21 @@ -import { Strategy } from "passport-local"; -import { Injectable, UnauthorizedException } from "@nestjs/common"; -import { PassportStrategy } from "@nestjs/passport"; -import { AuthService } from "../auth.service"; - +import { Strategy } from 'passport-local'; +import { Injectable, UnauthorizedException } from '@nestjs/common'; +import { PassportStrategy } from '@nestjs/passport'; +import { AuthService } from '../auth.service'; @Injectable() export class LocalStrategy extends PassportStrategy(Strategy) { - constructor( - private readonly authService: AuthService - ) { + constructor(private readonly authService: AuthService) { super({ usernameField: 'email', // 'username' - passwordField: 'password' // 'passport' + passwordField: 'password', // 'passport' }); } async validate(email: string, password: string) { const user = await this.authService.validateUser(email, password); - if (!user) throw new UnauthorizedException('Login user or password does not match.'); + if (!user) + throw new UnauthorizedException('Login user or password does not match.'); return user; } - -} \ No newline at end of file +} diff --git a/src/common/decorators/auth.decorator.ts b/src/common/decorators/auth.decorator.ts index 7668f20..a6ce261 100644 --- a/src/common/decorators/auth.decorator.ts +++ b/src/common/decorators/auth.decorator.ts @@ -1,13 +1,12 @@ -import { applyDecorators, UseGuards } from "@nestjs/common"; -import { ApiBearerAuth } from "@nestjs/swagger"; -import { JwtAuthGuard } from "src/auth/guards"; -import { ACGuard, Role, UseRoles } from "nest-access-control"; - +import { applyDecorators, UseGuards } from '@nestjs/common'; +import { ApiBearerAuth } from '@nestjs/swagger'; +import { JwtAuthGuard } from 'src/auth/guards'; +import { ACGuard, Role, UseRoles } from 'nest-access-control'; export function Auth(...roles: Role[]) { return applyDecorators( UseGuards(JwtAuthGuard, ACGuard), UseRoles(...roles), - ApiBearerAuth() - ) -} \ No newline at end of file + ApiBearerAuth(), + ); +} diff --git a/src/common/decorators/index.ts b/src/common/decorators/index.ts index 229536b..1cbadc7 100644 --- a/src/common/decorators/index.ts +++ b/src/common/decorators/index.ts @@ -1,2 +1,2 @@ export * from './user.decorator'; -export * from './auth.decorator'; \ No newline at end of file +export * from './auth.decorator'; diff --git a/src/common/decorators/user.decorator.ts b/src/common/decorators/user.decorator.ts index 43a0f2d..16675a9 100644 --- a/src/common/decorators/user.decorator.ts +++ b/src/common/decorators/user.decorator.ts @@ -7,4 +7,4 @@ export const User = createParamDecorator( return data ? user && user[data] : user; }, -); \ No newline at end of file +); diff --git a/src/config/constants.ts b/src/config/constants.ts index 4be99a3..751c09e 100644 --- a/src/config/constants.ts +++ b/src/config/constants.ts @@ -6,4 +6,4 @@ export const DATABASE_USERNAME = 'DATABASE_USERNAME'; export const DATABASE_PASSWORD = 'DATABASE_PASSWORD'; export const DATABASE_NAME = 'DATABASE_NAME'; export const DEFAULT_USER_EMAIL = 'DEFAULT_USER_EMAIL'; -export const DEFAULT_USER_PASSWORD = 'DEFAULT_USER_PASSWORD'; \ No newline at end of file +export const DEFAULT_USER_PASSWORD = 'DEFAULT_USER_PASSWORD'; diff --git a/src/config/default-user.ts b/src/config/default-user.ts index 5cdcd18..049e880 100644 --- a/src/config/default-user.ts +++ b/src/config/default-user.ts @@ -1,23 +1,25 @@ -import { getRepository } from 'typeorm' -import { ConfigService } from '@nestjs/config' -import { DEFAULT_USER_EMAIL, DEFAULT_USER_PASSWORD } from './constants' -import { User } from 'src/user/entities' +import { getRepository } from 'typeorm'; +import { ConfigService } from '@nestjs/config'; +import { DEFAULT_USER_EMAIL, DEFAULT_USER_PASSWORD } from './constants'; +import { User } from 'src/user/entities'; export const setDefaultUser = async (config: ConfigService) => { - const userRepository = getRepository(User) + const userRepository = getRepository(User); const defaultUser = await userRepository .createQueryBuilder() - .where('email = :email', { email: config.get('DEFAULT_USER_EMAIL') }) - .getOne() - + .where('email = :email', { + email: config.get('DEFAULT_USER_EMAIL'), + }) + .getOne(); + if (!defaultUser) { const adminUser = userRepository.create({ email: config.get(DEFAULT_USER_EMAIL), password: config.get(DEFAULT_USER_PASSWORD), - roles: ['ADMIN'] - }) + roles: ['ADMIN'], + }); - return await userRepository.save(adminUser) + return await userRepository.save(adminUser); } -} +}; diff --git a/src/post/entities/post.entity.ts b/src/post/entities/post.entity.ts index 861118d..074a236 100644 --- a/src/post/entities/post.entity.ts +++ b/src/post/entities/post.entity.ts @@ -37,7 +37,11 @@ export class Post { @CreateDateColumn({ type: 'timestamp' }) createdAt: Date; - @ManyToOne(_ => User, (user) => user.posts, { eager: true }) + @ManyToOne( + () => User, + user => user.posts, + { eager: true }, + ) @JoinColumn({ name: 'author' }) author: User; } diff --git a/src/post/post.controller.ts b/src/post/post.controller.ts index 8602bcd..bc86616 100644 --- a/src/post/post.controller.ts +++ b/src/post/post.controller.ts @@ -23,8 +23,8 @@ export class PostController { private readonly postService: PostService, @InjectRolesBuilder() private readonly roleBuilder: RolesBuilder, - ) {} - + ) {} + @Get() async getMany() { const data = await this.postService.getMany(); @@ -40,13 +40,10 @@ export class PostController { @Auth({ resource: AppResource.POST, action: 'create', - possession: 'own' + possession: 'own', }) @Post() - async createPost( - @Body() dto: CreatePostDto, - @User() author: UserEntity - ) { + async createPost(@Body() dto: CreatePostDto, @User() author: UserEntity) { const data = await this.postService.createOne(dto, author); return { message: 'Post created', data }; } @@ -54,53 +51,41 @@ export class PostController { @Auth({ resource: AppResource.POST, action: 'update', - possession: 'own' + possession: 'own', }) @Put(':id') async editOne( - @Param('id') id: number, @Body() dto: EditPostDto, - @User() author: UserEntity + @Param('id') id: number, + @Body() dto: EditPostDto, + @User() author: UserEntity, ) { - let data; if ( - this.roleBuilder - .can(author.roles) - .updateAny(AppResource.POST) - .granted - ) { - + this.roleBuilder.can(author.roles).updateAny(AppResource.POST).granted + ) { // Puede editar cualquier POST... data = await this.postService.editOne(id, dto); - } else { - // Puede editar solo los propios... data = await this.postService.editOne(id, dto, author); } - + return { message: 'Post edited', data }; } @Auth({ resource: AppResource.POST, action: 'delete', - possession: 'own' + possession: 'own', }) @Delete(':id') - async deleteOne( - @Param('id') id: number, - @User() author: UserEntity - ) { - + async deleteOne(@Param('id') id: number, @User() author: UserEntity) { let data; - if (this.roleBuilder - .can(author.roles) - .deleteAny(AppResource.POST) - .granted - ) { + if ( + this.roleBuilder.can(author.roles).deleteAny(AppResource.POST).granted + ) { data = await this.postService.deleteOne(id); } else { data = await this.postService.deleteOne(id, author); diff --git a/src/post/post.service.ts b/src/post/post.service.ts index ae6a552..9234662 100644 --- a/src/post/post.service.ts +++ b/src/post/post.service.ts @@ -18,14 +18,16 @@ export class PostService { } async getById(id: number, author?: User) { - const post = await this.postRepository.findOne(id) - .then(p => !author ? p : !!p && author.id === p.author.id ? p : null) - if (!post) throw new NotFoundException('Post does not exist or unauthorized'); + const post = await this.postRepository + .findOne(id) + .then(p => (!author ? p : !!p && author.id === p.author.id ? p : null)); + if (!post) + throw new NotFoundException('Post does not exist or unauthorized'); return post; } async createOne(dto: CreatePostDto, author: User) { - const post = this.postRepository.create({...dto, author}); + const post = this.postRepository.create({ ...dto, author }); return await this.postRepository.save(post); } diff --git a/src/user/dtos/create-user.dto.ts b/src/user/dtos/create-user.dto.ts index ed2960c..be7e31e 100644 --- a/src/user/dtos/create-user.dto.ts +++ b/src/user/dtos/create-user.dto.ts @@ -1,6 +1,14 @@ -import { IsString, IsEmail, MinLength, MaxLength, IsOptional, IsArray, IsEnum } from "class-validator"; -import { AppRoles } from "src/app.roles"; -import { EnumToString } from "src/common/helpers/enumToString"; +import { + IsString, + IsEmail, + MinLength, + MaxLength, + IsOptional, + IsArray, + IsEnum, +} from 'class-validator'; +import { AppRoles } from 'src/app.roles'; +import { EnumToString } from 'src/common/helpers/enumToString'; export class CreateUserDto { @IsOptional() @@ -24,8 +32,7 @@ export class CreateUserDto { @IsArray() @IsEnum(AppRoles, { each: true, - message: `must be a valid role value, ${ EnumToString(AppRoles)}` + message: `must be a valid role value, ${EnumToString(AppRoles)}`, }) roles: string[]; - } diff --git a/src/user/dtos/edit-user.dto.ts b/src/user/dtos/edit-user.dto.ts index 8e63be2..c6cbfcd 100644 --- a/src/user/dtos/edit-user.dto.ts +++ b/src/user/dtos/edit-user.dto.ts @@ -1,4 +1,4 @@ -import { PartialType } from "@nestjs/mapped-types"; -import { CreateUserDto } from "./create-user.dto"; +import { PartialType } from '@nestjs/mapped-types'; +import { CreateUserDto } from './create-user.dto'; export class EditUserDto extends PartialType(CreateUserDto) {} diff --git a/src/user/dtos/index.ts b/src/user/dtos/index.ts index ed7b214..55bab43 100644 --- a/src/user/dtos/index.ts +++ b/src/user/dtos/index.ts @@ -1,3 +1,3 @@ export * from './create-user.dto'; export * from './edit-user.dto'; -export * from './user-registration.dto'; \ No newline at end of file +export * from './user-registration.dto'; diff --git a/src/user/dtos/user-registration.dto.ts b/src/user/dtos/user-registration.dto.ts index 4a3c5fe..107884d 100644 --- a/src/user/dtos/user-registration.dto.ts +++ b/src/user/dtos/user-registration.dto.ts @@ -1,4 +1,6 @@ -import { OmitType } from "@nestjs/mapped-types"; -import { CreateUserDto } from "./create-user.dto"; +import { OmitType } from '@nestjs/mapped-types'; +import { CreateUserDto } from './create-user.dto'; -export class UserRegistrationDto extends OmitType(CreateUserDto, ['roles'] as const) {} +export class UserRegistrationDto extends OmitType(CreateUserDto, [ + 'roles', +] as const) {} diff --git a/src/user/entities/index.ts b/src/user/entities/index.ts index eee2434..e4aa507 100644 --- a/src/user/entities/index.ts +++ b/src/user/entities/index.ts @@ -1 +1 @@ -export * from './user.entity'; \ No newline at end of file +export * from './user.entity'; diff --git a/src/user/entities/user.entity.ts b/src/user/entities/user.entity.ts index f98c5c9..6ae9281 100644 --- a/src/user/entities/user.entity.ts +++ b/src/user/entities/user.entity.ts @@ -29,7 +29,7 @@ export class User { @Column({ type: 'simple-array' }) roles: string[]; - + @Column({ type: 'bool', default: true }) status: boolean; @@ -45,6 +45,10 @@ export class User { this.password = await hash(this.password, 10); } - @OneToOne(_ => Post, post => post.author, { cascade: true } ) + @OneToOne( + _ => Post, + post => post.author, + { cascade: true }, + ) posts: Post; } diff --git a/src/user/user.controller.ts b/src/user/user.controller.ts index f55ed39..fbe4952 100644 --- a/src/user/user.controller.ts +++ b/src/user/user.controller.ts @@ -1,4 +1,12 @@ -import { Controller, Get, Post, Put, Delete, Param, Body } from '@nestjs/common'; +import { + Controller, + Get, + Post, + Put, + Delete, + Param, + Body, +} from '@nestjs/common'; import { UserService } from './user.service'; import { CreateUserDto, EditUserDto, UserRegistrationDto } from './dtos'; import { Auth, User } from 'src/common/decorators'; @@ -10,105 +18,84 @@ import { User as UserEntity } from './entities'; @ApiTags('Users routes') @Controller('user') export class UserController { - constructor( private readonly userService: UserService, @InjectRolesBuilder() - private readonly rolesBuilder: RolesBuilder + private readonly rolesBuilder: RolesBuilder, ) {} @Get() async getMany() { const data = await this.userService.getMany(); - return { data } + return { data }; } @Post('register') - async publicRegistration( - @Body() dto: UserRegistrationDto - ) { + async publicRegistration(@Body() dto: UserRegistrationDto) { const data = await this.userService.createOne({ - ...dto, roles: [AppRoles.AUTHOR] + ...dto, + roles: [AppRoles.AUTHOR], }); - return { message: 'User registered', data } + return { message: 'User registered', data }; } @Get(':id') - async getOne( - @Param('id') id: number, - ) { + async getOne(@Param('id') id: number) { const data = await this.userService.getOne(id); - return { data } + return { data }; } @Auth({ possession: 'any', action: 'create', - resource: AppResource.USER + resource: AppResource.USER, }) @Post() - async createOne( - @Body() dto: CreateUserDto - ) { - const data = await this.userService.createOne(dto) - return { message: 'User created', data } + async createOne(@Body() dto: CreateUserDto) { + const data = await this.userService.createOne(dto); + return { message: 'User created', data }; } @Auth({ possession: 'own', action: 'update', - resource: AppResource.USER + resource: AppResource.USER, }) @Put(':id') async editOne( @Param('id') id: number, @Body() dto: EditUserDto, - @User() user: UserEntity + @User() user: UserEntity, ) { - let data; - if(this.rolesBuilder - .can(user.roles) - .updateAny(AppResource.USER) - .granted - ) { + if (this.rolesBuilder.can(user.roles).updateAny(AppResource.USER).granted) { // esto es un admin - data = await this.userService.editOne(id, dto) + data = await this.userService.editOne(id, dto); } else { // esto es un author const { roles, ...rest } = dto; - data = await this.userService.editOne(id, rest, user) + data = await this.userService.editOne(id, rest, user); } - return { message: 'User edited', data } + return { message: 'User edited', data }; } @Auth({ action: 'delete', possession: 'own', - resource: AppResource.USER + resource: AppResource.USER, }) @Delete(':id') - async deleteOne( - @Param('id') id: number, - @User() user: UserEntity - ) { - + async deleteOne(@Param('id') id: number, @User() user: UserEntity) { let data; - if(this.rolesBuilder - .can(user.roles) - .updateAny(AppResource.USER) - .granted - ) { + if (this.rolesBuilder.can(user.roles).updateAny(AppResource.USER).granted) { // esto es un admin - data = await this.userService.deleteOne(id) + data = await this.userService.deleteOne(id); } else { // esto es un author - data = await this.userService.deleteOne(id, user) + data = await this.userService.deleteOne(id, user); } - return { message: 'User deleted', data } + return { message: 'User deleted', data }; } - - } diff --git a/src/user/user.module.ts b/src/user/user.module.ts index f967e7d..d9c48cb 100644 --- a/src/user/user.module.ts +++ b/src/user/user.module.ts @@ -5,11 +5,9 @@ import { TypeOrmModule } from '@nestjs/typeorm'; import { User } from './entities'; @Module({ - imports: [ - TypeOrmModule.forFeature([User]) - ], + imports: [TypeOrmModule.forFeature([User])], controllers: [UserController], providers: [UserService], - exports: [UserService] + exports: [UserService], }) export class UserModule {} diff --git a/src/user/user.service.ts b/src/user/user.service.ts index 5b66b20..ef1621f 100644 --- a/src/user/user.service.ts +++ b/src/user/user.service.ts @@ -1,4 +1,8 @@ -import { Injectable, NotFoundException, BadRequestException } from '@nestjs/common'; +import { + Injectable, + NotFoundException, + BadRequestException, +} from '@nestjs/common'; import { Repository } from 'typeorm'; import { User } from './entities'; import { InjectRepository } from '@nestjs/typeorm'; @@ -11,43 +15,45 @@ export interface UserFindOne { @Injectable() export class UserService { - constructor( @InjectRepository(User) - private readonly userRepository: Repository + private readonly userRepository: Repository, ) {} async getMany() { - return await this.userRepository.find() + return await this.userRepository.find(); } - + async getOne(id: number, userEntity?: User) { - const user = await this.userRepository.findOne(id) - .then(u => !userEntity ? u : !!u && userEntity.id === u.id ? u : null) - - if (!user) throw new NotFoundException('User does not exists or unauthorized') + const user = await this.userRepository + .findOne(id) + .then(u => (!userEntity ? u : !!u && userEntity.id === u.id ? u : null)); + + if (!user) + throw new NotFoundException('User does not exists or unauthorized'); return user; } - + async createOne(dto: CreateUserDto) { const userExist = await this.userRepository.findOne({ email: dto.email }); - if (userExist) throw new BadRequestException('User already registered with email'); + if (userExist) + throw new BadRequestException('User already registered with email'); - const newUser = this.userRepository.create(dto) - const user = await this.userRepository.save(newUser) + const newUser = this.userRepository.create(dto); + const user = await this.userRepository.save(newUser); delete user.password; return user; } - + async editOne(id: number, dto: EditUserDto, userEntity?: User) { console.log(dto); - const user = await this.getOne(id, userEntity) + const user = await this.getOne(id, userEntity); const editedUser = Object.assign(user, dto); return await this.userRepository.save(editedUser); } - + async deleteOne(id: number, userEntity?: User) { const user = await this.getOne(id, userEntity); return await this.userRepository.remove(user); @@ -58,6 +64,6 @@ export class UserService { .createQueryBuilder('user') .where(data) .addSelect('user.password') - .getOne() + .getOne(); } }