Skip to content

Commit ab2b9d9

Browse files
committed
Add POST /user/update
1 parent 6d862fe commit ab2b9d9

File tree

4 files changed

+67
-9
lines changed

4 files changed

+67
-9
lines changed

src/dto/user.dto.ts

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { ApiProperty } from '@nestjs/swagger';
2-
import {IsString} from 'class-validator';
2+
import {IsString, MaxLength} from 'class-validator';
33
import {Transform, Type} from "class-transformer";
44

55
export class AddUserDto {
@@ -23,3 +23,14 @@ export class GetUsersDto {
2323
@IsString()
2424
offset: number;
2525
}
26+
27+
const UsernameMaxLength = 20
28+
29+
export class UpdateUserDto {
30+
@ApiProperty({ type: String, required: true, default: '' })
31+
@Transform((address) => address.value.trim().toLowerCase())
32+
@MaxLength(UsernameMaxLength, { message: `username must not exceed ${UsernameMaxLength} characters` })
33+
@Type(() => String)
34+
@IsString()
35+
username: string;
36+
}

src/entities/user-account.entity.ts

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@ import {
66
PrimaryGeneratedColumn,
77
UpdateDateColumn,
88
ManyToMany,
9-
JoinTable, ManyToOne
109
} from 'typeorm';
1110
import { ApiProperty } from '@nestjs/swagger';
1211
import {Token} from "./token.entity";
@@ -24,7 +23,7 @@ export class UserAccount {
2423
address: string;
2524

2625
@ApiProperty()
27-
@Column()
26+
@Column({ unique: true })
2827
username: string;
2928

3029
@OneToMany(() => Token, (token) => token.user)

src/user/user.controller.ts

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ import {UserService} from "./user.service";
1717
import {JwtTokenDto, JwtTokensDto} from "../dto/jwt.dto";
1818
import {instanceToPlain, plainToInstance} from "class-transformer";
1919
import {JwtService} from "@nestjs/jwt";
20-
import {AddUserDto} from "../dto/user.dto";
20+
import {UpdateUserDto} from "../dto/user.dto";
2121
import {JwtUserAccount} from "../entities/user-account.entity";
2222
import {AuthGuard} from "../common/auth.guard";
2323

@@ -170,4 +170,26 @@ export class UserController {
170170
async getUserTokensCreated(@Param('address') userAddress: string) {
171171
return await this.userService.getTokensCreated(userAddress)
172172
}
173+
174+
@Post('/update')
175+
@UseGuards(AuthGuard)
176+
@ApiBearerAuth()
177+
@UsePipes(new ValidationPipe(validationCfg()))
178+
async updateUser(@Request() req, @Body() dto: UpdateUserDto) {
179+
if(!req.user) {
180+
throw new BadRequestException('InvalidJWT')
181+
}
182+
const { address } = plainToInstance(JwtUserAccount, req.user)
183+
const user = await this.userService.getUserByAddress(address)
184+
if(!user) {
185+
throw new NotFoundException('User not found')
186+
}
187+
const existedUsername = await this.userService.getUserByUsername(dto.username)
188+
if(existedUsername) {
189+
throw new BadRequestException('Username already exist')
190+
}
191+
const updatedUser = await this.userService.updateUser(address, dto);
192+
this.logger.log(`User ${address} successfully updated: "${JSON.stringify(updatedUser)}"`)
193+
return updatedUser
194+
}
173195
}

src/user/user.service.ts

Lines changed: 31 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1-
import { Injectable } from '@nestjs/common';
1+
import {Injectable, NotFoundException} from '@nestjs/common';
22
import {DataSource, EntityManager} from "typeorm";
33
import {SignInRequestEntity, Token, UserAccount} from "../entities";
4-
import {AddUserDto, GetUsersDto} from "../dto/user.dto";
4+
import {AddUserDto, UpdateUserDto} from "../dto/user.dto";
55
import {generateNonce} from "../utils";
66
import {VerifySignatureDto} from "../dto/account.dto";
77
import {verifyMessage} from "ethers";
@@ -83,15 +83,33 @@ export class UserService {
8383
}
8484

8585
async createUser(dto: AddUserDto, entityManager?: EntityManager) {
86-
const { address } = dto
86+
const address = dto.address.toLowerCase()
87+
let username = address.replaceAll('0x', '').slice(0, 6)
88+
89+
const existedUsername = await this.getUserByUsername(username, entityManager)
90+
if(existedUsername) {
91+
username = address
92+
}
8793

8894
const data = await (entityManager || this.dataSource.manager).insert(UserAccount, {
89-
address: address.toLowerCase(),
90-
username: address.replaceAll('0x', '').slice(0, 6)
95+
address,
96+
username
9197
})
9298
return data.identifiers[0].id
9399
}
94100

101+
async updateUser(address: string, dto: UpdateUserDto) {
102+
const user = await this.dataSource.manager.findOne(UserAccount, {
103+
where: {
104+
address
105+
}
106+
})
107+
return await this.dataSource.getRepository(UserAccount).save({
108+
...user,
109+
username: dto.username,
110+
})
111+
}
112+
95113
async getUserByAddress(address: string, entityManager?: EntityManager) {
96114
return await (entityManager || this.dataSource.manager).findOne(UserAccount, {
97115
where: {
@@ -100,6 +118,14 @@ export class UserService {
100118
})
101119
}
102120

121+
async getUserByUsername(username: string, entityManager?: EntityManager) {
122+
return await (entityManager || this.dataSource.manager).findOne(UserAccount, {
123+
where: {
124+
username,
125+
},
126+
})
127+
}
128+
103129
async getTokensCreated(userAddress: string) {
104130
return await this.dataSource.manager.find(Token, {
105131
relations: ['user'],

0 commit comments

Comments
 (0)