Skip to content

Commit

Permalink
Add POST /user/update
Browse files Browse the repository at this point in the history
  • Loading branch information
ArtemKolodko committed Nov 15, 2024
1 parent 6d862fe commit ab2b9d9
Show file tree
Hide file tree
Showing 4 changed files with 67 additions and 9 deletions.
13 changes: 12 additions & 1 deletion src/dto/user.dto.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { ApiProperty } from '@nestjs/swagger';
import {IsString} from 'class-validator';
import {IsString, MaxLength} from 'class-validator';
import {Transform, Type} from "class-transformer";

export class AddUserDto {
Expand All @@ -23,3 +23,14 @@ export class GetUsersDto {
@IsString()
offset: number;
}

const UsernameMaxLength = 20

export class UpdateUserDto {
@ApiProperty({ type: String, required: true, default: '' })
@Transform((address) => address.value.trim().toLowerCase())
@MaxLength(UsernameMaxLength, { message: `username must not exceed ${UsernameMaxLength} characters` })
@Type(() => String)
@IsString()
username: string;
}
3 changes: 1 addition & 2 deletions src/entities/user-account.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import {
PrimaryGeneratedColumn,
UpdateDateColumn,
ManyToMany,
JoinTable, ManyToOne
} from 'typeorm';
import { ApiProperty } from '@nestjs/swagger';
import {Token} from "./token.entity";
Expand All @@ -24,7 +23,7 @@ export class UserAccount {
address: string;

@ApiProperty()
@Column()
@Column({ unique: true })
username: string;

@OneToMany(() => Token, (token) => token.user)
Expand Down
24 changes: 23 additions & 1 deletion src/user/user.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import {UserService} from "./user.service";
import {JwtTokenDto, JwtTokensDto} from "../dto/jwt.dto";
import {instanceToPlain, plainToInstance} from "class-transformer";
import {JwtService} from "@nestjs/jwt";
import {AddUserDto} from "../dto/user.dto";
import {UpdateUserDto} from "../dto/user.dto";
import {JwtUserAccount} from "../entities/user-account.entity";
import {AuthGuard} from "../common/auth.guard";

Expand Down Expand Up @@ -170,4 +170,26 @@ export class UserController {
async getUserTokensCreated(@Param('address') userAddress: string) {
return await this.userService.getTokensCreated(userAddress)
}

@Post('/update')
@UseGuards(AuthGuard)
@ApiBearerAuth()
@UsePipes(new ValidationPipe(validationCfg()))
async updateUser(@Request() req, @Body() dto: UpdateUserDto) {
if(!req.user) {
throw new BadRequestException('InvalidJWT')
}
const { address } = plainToInstance(JwtUserAccount, req.user)
const user = await this.userService.getUserByAddress(address)
if(!user) {
throw new NotFoundException('User not found')
}
const existedUsername = await this.userService.getUserByUsername(dto.username)
if(existedUsername) {
throw new BadRequestException('Username already exist')
}
const updatedUser = await this.userService.updateUser(address, dto);
this.logger.log(`User ${address} successfully updated: "${JSON.stringify(updatedUser)}"`)
return updatedUser
}
}
36 changes: 31 additions & 5 deletions src/user/user.service.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Injectable } from '@nestjs/common';
import {Injectable, NotFoundException} from '@nestjs/common';
import {DataSource, EntityManager} from "typeorm";
import {SignInRequestEntity, Token, UserAccount} from "../entities";
import {AddUserDto, GetUsersDto} from "../dto/user.dto";
import {AddUserDto, UpdateUserDto} from "../dto/user.dto";
import {generateNonce} from "../utils";
import {VerifySignatureDto} from "../dto/account.dto";
import {verifyMessage} from "ethers";
Expand Down Expand Up @@ -83,15 +83,33 @@ export class UserService {
}

async createUser(dto: AddUserDto, entityManager?: EntityManager) {
const { address } = dto
const address = dto.address.toLowerCase()
let username = address.replaceAll('0x', '').slice(0, 6)

const existedUsername = await this.getUserByUsername(username, entityManager)
if(existedUsername) {
username = address
}

const data = await (entityManager || this.dataSource.manager).insert(UserAccount, {
address: address.toLowerCase(),
username: address.replaceAll('0x', '').slice(0, 6)
address,
username
})
return data.identifiers[0].id
}

async updateUser(address: string, dto: UpdateUserDto) {
const user = await this.dataSource.manager.findOne(UserAccount, {
where: {
address
}
})
return await this.dataSource.getRepository(UserAccount).save({
...user,
username: dto.username,
})
}

async getUserByAddress(address: string, entityManager?: EntityManager) {
return await (entityManager || this.dataSource.manager).findOne(UserAccount, {
where: {
Expand All @@ -100,6 +118,14 @@ export class UserService {
})
}

async getUserByUsername(username: string, entityManager?: EntityManager) {
return await (entityManager || this.dataSource.manager).findOne(UserAccount, {
where: {
username,
},
})
}

async getTokensCreated(userAddress: string) {
return await this.dataSource.manager.find(Token, {
relations: ['user'],
Expand Down

0 comments on commit ab2b9d9

Please sign in to comment.