1+ import { Type } from 'class-transformer' ;
2+ import { IsEmail , IsNotEmpty , IsUUID , ValidateNested } from 'class-validator' ;
13import {
24 Authorized , Body , Delete , Get , JsonController , OnUndefined , Param , Post , Put , Req
35} from 'routing-controllers' ;
6+ import { ResponseSchema } from 'routing-controllers-openapi' ;
47
58import { UserNotFoundError } from '../errors/UserNotFoundError' ;
69import { User } from '../models/User' ;
710import { UserService } from '../services/UserService' ;
11+ import { PetResponse } from './PetController' ;
12+
13+ class BaseUser {
14+ @IsNotEmpty ( )
15+ public firstName : string ;
16+
17+ @IsNotEmpty ( )
18+ public lastName : string ;
19+
20+ @IsEmail ( )
21+ @IsNotEmpty ( )
22+ public email : string ;
23+
24+ @IsNotEmpty ( )
25+ public username : string ;
26+ }
27+
28+ export class UserResponse extends BaseUser {
29+ @IsUUID ( )
30+ public id : string ;
31+
32+ @ValidateNested ( { each : true } )
33+ @Type ( ( ) => PetResponse )
34+ public pets : PetResponse [ ] ;
35+ }
36+
37+ class CreateUserBody extends BaseUser {
38+ @IsNotEmpty ( )
39+ public password : string ;
40+ }
841
942@Authorized ( )
1043@JsonController ( '/users' )
@@ -15,28 +48,46 @@ export class UserController {
1548 ) { }
1649
1750 @Get ( )
51+ @ResponseSchema ( UserResponse , { isArray : true } )
1852 public find ( ) : Promise < User [ ] > {
1953 return this . userService . find ( ) ;
2054 }
2155
2256 @Get ( '/me' )
57+ @ResponseSchema ( UserResponse , { isArray : true } )
2358 public findMe ( @Req ( ) req : any ) : Promise < User [ ] > {
2459 return req . user ;
2560 }
2661
2762 @Get ( '/:id' )
2863 @OnUndefined ( UserNotFoundError )
64+ @ResponseSchema ( UserResponse )
2965 public one ( @Param ( 'id' ) id : string ) : Promise < User | undefined > {
3066 return this . userService . findOne ( id ) ;
3167 }
3268
3369 @Post ( )
34- public create ( @Body ( ) user : User ) : Promise < User > {
70+ @ResponseSchema ( UserResponse )
71+ public create ( @Body ( ) body : CreateUserBody ) : Promise < User > {
72+ const user = new User ( ) ;
73+ user . email = body . email ;
74+ user . firstName = body . firstName ;
75+ user . lastName = body . lastName ;
76+ user . password = body . password ;
77+ user . username = body . username ;
78+
3579 return this . userService . create ( user ) ;
3680 }
3781
3882 @Put ( '/:id' )
39- public update ( @Param ( 'id' ) id : string , @Body ( ) user : User ) : Promise < User > {
83+ @ResponseSchema ( UserResponse )
84+ public update ( @Param ( 'id' ) id : string , @Body ( ) body : BaseUser ) : Promise < User > {
85+ const user = new User ( ) ;
86+ user . email = body . email ;
87+ user . firstName = body . firstName ;
88+ user . lastName = body . lastName ;
89+ user . username = body . username ;
90+
4091 return this . userService . update ( id , user ) ;
4192 }
4293
0 commit comments