-
Notifications
You must be signed in to change notification settings - Fork 915
/
Copy pathUserController.ts
106 lines (86 loc) · 2.76 KB
/
UserController.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
import { Type } from 'class-transformer';
import { IsEmail, IsNotEmpty, IsUUID, ValidateNested } from 'class-validator';
import {
Authorized, Body, Delete, Get, JsonController, OnUndefined, Param, Post, Put, QueryParam, Req
} from 'routing-controllers';
import { OpenAPI, ResponseSchema } from 'routing-controllers-openapi';
import { UserNotFoundError } from '../errors/UserNotFoundError';
import { User } from '../models/User';
import { UserService } from '../services/UserService';
import { PetResponse } from './PetController';
class BaseUser {
@IsNotEmpty()
public firstName: string;
@IsNotEmpty()
public lastName: string;
@IsEmail()
@IsNotEmpty()
public email: string;
@IsNotEmpty()
public username: string;
}
export class UserResponse extends BaseUser {
@IsUUID()
public id: string;
@ValidateNested({ each: true })
@Type(() => PetResponse)
public pets: PetResponse[];
}
class CreateUserBody extends BaseUser {
@IsNotEmpty()
public password: string;
}
@Authorized()
@JsonController('/users')
@OpenAPI({ security: [{ basicAuth: [] }] })
export class UserController {
constructor(
private userService: UserService
) { }
@Get()
@ResponseSchema(UserResponse, { isArray: true })
public find(): Promise<User[]> {
return this.userService.find();
}
@Get('/me')
@ResponseSchema(UserResponse, { isArray: true })
public findMe(@Req() req: any): Promise<User[]> {
return req.user;
}
@Get('/:id')
@OnUndefined(UserNotFoundError)
@ResponseSchema(UserResponse)
public one(@Param('id') id: string): Promise<User | undefined> {
return this.userService.findOne(id);
}
@Get('/search')
@ResponseSchema(UserResponse, { isArray: true })
public search(@QueryParam('query') query: string): Promise<User[]> {
return this.userService.search(query);
}
@Post()
@ResponseSchema(UserResponse)
public create(@Body() body: CreateUserBody): Promise<User> {
const user = new User();
user.email = body.email;
user.firstName = body.firstName;
user.lastName = body.lastName;
user.password = body.password;
user.username = body.username;
return this.userService.create(user);
}
@Put('/:id')
@ResponseSchema(UserResponse)
public update(@Param('id') id: string, @Body() body: BaseUser): Promise<User> {
const user = new User();
user.email = body.email;
user.firstName = body.firstName;
user.lastName = body.lastName;
user.username = body.username;
return this.userService.update(id, user);
}
@Delete('/:id')
public delete(@Param('id') id: string): Promise<void> {
return this.userService.delete(id);
}
}