-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontroller.ts
More file actions
114 lines (101 loc) · 2.5 KB
/
Copy pathcontroller.ts
File metadata and controls
114 lines (101 loc) · 2.5 KB
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
107
108
109
110
111
112
113
114
import {
Body,
Controller,
Delete,
Description,
Get,
NotFoundException,
Param,
Patch,
Post,
Query,
Returns,
Route,
Summary,
Tags,
} from "../../src/index.js";
import {
CreateUser,
ErrorResponse,
ListQuery,
UpdateUser,
User,
UserParams,
} from "./schemas.js";
// In-memory store for demo purposes
const users = new Map<string, { id: string; name: string; email: string; createdAt: string; }>();
@Route("/users")
@Tags("Users")
export class UserController extends Controller {
@Get()
@Summary("List users")
@Description("Returns a paginated list of users, optionally filtered by search term")
@Returns(200, [User], "List of users")
list(@Query(ListQuery) query: ListQuery) {
let results = [...users.values()];
if (query.search) {
const term = query.search.toLowerCase();
results = results.filter(
(u) => u.name.toLowerCase().includes(term) || u.email.toLowerCase().includes(term),
);
}
const page = query.page ?? 1;
const limit = query.limit ?? 20;
const start = (page - 1) * limit;
return results.slice(start, start + limit);
}
@Get("/:id")
@Summary("Get user by ID")
@Returns(200, User, "The user")
@Returns(404, ErrorResponse, "User not found")
getById(@Param(UserParams) params: UserParams) {
const user = users.get(params.id);
if (!user) {
throw new NotFoundException("User not found");
}
return user;
}
@Post()
@Summary("Create a new user")
@Returns(201, User, "Created user")
@Returns(400, ErrorResponse, "Validation error")
create(@Body(CreateUser) body: CreateUser) {
const id = crypto.randomUUID();
const user = {
id: id,
name: body.name,
email: body.email,
createdAt: new Date().toISOString(),
};
users.set(id, user);
this.setStatus(201);
return user;
}
@Patch("/:id")
@Summary("Update a user")
@Returns(200, User, "Updated user")
@Returns(404, ErrorResponse, "User not found")
update(
@Param(UserParams) params: UserParams,
@Body(UpdateUser) body: UpdateUser,
) {
const user = users.get(params.id);
if (!user) {
throw new NotFoundException("User not found");
}
if (body.name !== undefined) user.name = body.name;
if (body.email !== undefined) user.email = body.email;
return user;
}
@Delete("/:id")
@Summary("Delete a user")
@Returns(204, undefined, "User deleted")
@Returns(404, ErrorResponse, "User not found")
remove(@Param(UserParams) params: UserParams) {
if (!users.has(params.id)) {
throw new NotFoundException("User not found");
}
users.delete(params.id);
this.setStatus(204);
}
}