-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathapplication-controller.ts
More file actions
350 lines (319 loc) · 9.29 KB
/
application-controller.ts
File metadata and controls
350 lines (319 loc) · 9.29 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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
import {
Authorized,
BadRequestError,
Body,
CurrentUser,
Delete,
Get,
JsonController,
NotAcceptableError,
NotFoundError,
Param,
Post,
Put,
} from "routing-controllers";
import { Inject } from "typedi";
import { User } from "../entities/user";
import { UserRole } from "../entities/user-role";
import {
AlreadyAdmittedError,
AlreadyDeclinedError,
ApplicationServiceToken,
FormNotAvailableError,
IApplicationService,
IForm,
IncompleteProfileFormError,
InvalidAnswerError,
IRawAnswer,
NotAdmittedError,
ProfileFormNotSubmittedError,
QuestionNotAnsweredError,
QuestionNotFoundError,
} from "../services/application-service";
import { IUserService, UserServiceToken } from "../services/user-service";
import {
AnswerDTO,
ApplicationDTO,
convertBetweenEntityAndDTO,
FormDTO,
IDRequestDTO,
IDsRequestDTO,
QuestionDTO,
StoreAnswersRequestDTO,
SuccessResponseDTO,
TeamDTO,
TeamRequestDTO,
TeamResponseDTO,
TeamUpdateDTO,
} from "./dto";
import { ITeamService, TeamServiceToken } from "../services/team-service";
import { Team } from "../entities/team";
@JsonController("/application")
export class ApplicationController {
public constructor(
@Inject(ApplicationServiceToken)
private readonly _application: IApplicationService,
@Inject(UserServiceToken)
private readonly _users: IUserService,
@Inject(TeamServiceToken)
private readonly _teams: ITeamService,
) {}
/**
* Converts a form from the internal representation to DTO.
* @param form A form received from the `IApplicationService`
*/
private convertFormToDTO(form: IForm): FormDTO {
const dto = new FormDTO();
dto.questions = form.questions.map((question) =>
convertBetweenEntityAndDTO(question, QuestionDTO),
);
dto.answers = form.answers.map((answer) =>
convertBetweenEntityAndDTO(answer, AnswerDTO),
);
return dto;
}
/**
* Converts request answers to raw answers for the service.
* @param answerDTOs The answers from the request
*/
private convertAnswerDTOsToRawAnswers(
answerDTOs: readonly AnswerDTO[],
): readonly IRawAnswer[] {
return answerDTOs.map<IRawAnswer>(({ questionID, value }) => ({
questionID,
value,
}));
}
/**
* Wraps a service error to an HTTP error.
* @param error The error received from the service
*/
private convertErrorToHTTP(error: unknown): Error {
if (error instanceof QuestionNotFoundError) {
return new NotFoundError(error.message);
} else if (
error instanceof AlreadyAdmittedError ||
error instanceof AlreadyDeclinedError ||
error instanceof IncompleteProfileFormError ||
error instanceof InvalidAnswerError ||
error instanceof NotAdmittedError ||
error instanceof ProfileFormNotSubmittedError ||
error instanceof QuestionNotAnsweredError ||
error instanceof QuestionNotFoundError
) {
return new BadRequestError(error.message);
} else if (error instanceof FormNotAvailableError) {
return new NotAcceptableError(error.message);
}
return new Error(String(error));
}
/**
* Gets the profile form for the given user.
* @param user The currently logged in user
*/
@Get("/profile")
@Authorized(UserRole.User)
public async getProfileForm(@CurrentUser() user: User): Promise<FormDTO> {
const form = await this._application.getProfileForm(user);
return this.convertFormToDTO(form);
}
/**
* Stores the given answers for the current user.
* @param user The currently logged in user
*/
@Post("/profile")
@Authorized(UserRole.User)
public async storeProfileFormAnswers(
@Body() { data: answerDTOs }: StoreAnswersRequestDTO,
@CurrentUser() user: User,
): Promise<void> {
const answers = this.convertAnswerDTOsToRawAnswers(answerDTOs);
try {
await this._application.storeProfileFormAnswers(user, answers);
} catch (error) {
throw this.convertErrorToHTTP(error);
}
}
/**
* Admits a list of users.
*/
@Put("/admit")
@Authorized(UserRole.Moderator)
public async admit(@Body() { data: userIDs }: IDsRequestDTO): Promise<void> {
const users = await this._users.findUsersByIDs(userIDs);
const firstMissingIndex = users.findIndex((user) => user == null);
if (firstMissingIndex !== -1) {
throw new NotFoundError(
`no user with id ${userIDs[firstMissingIndex]} found`,
);
}
try {
await this._application.admit(users as readonly User[]);
} catch (error) {
throw this.convertErrorToHTTP(error);
}
}
/**
* Gets the confirmation form with all not yet answered questions from the
* profile form.
* @param user The currently logged in user
*/
@Get("/confirm")
@Authorized(UserRole.User)
public async getConfirmationForm(
@CurrentUser() user: User,
): Promise<FormDTO> {
try {
const form = await this._application.getConfirmationForm(user);
return this.convertFormToDTO(form);
} catch (error) {
throw this.convertErrorToHTTP(error);
}
}
/**
* Stores the answers to the confirmation form.
* @param user The currently logged in user
*/
@Post("/confirm")
@Authorized(UserRole.User)
public async storeConfirmationFormAnswers(
@Body() { data: answerDTOs }: StoreAnswersRequestDTO,
@CurrentUser() user: User,
): Promise<void> {
const answers = this.convertAnswerDTOsToRawAnswers(answerDTOs);
try {
await this._application.storeConfirmationFormAnswers(user, answers);
} catch (error) {
throw this.convertErrorToHTTP(error);
}
}
/**
* Declines the spot of the current user.
* @param user The currently logged in user
*/
@Delete("/confirm")
@Authorized(UserRole.User)
public async declineSpot(@CurrentUser() user: User) {
await this._application.declineSpot(user);
}
/**
* Gets all existing application. This only includes applications where users
* actually applied.
*/
@Get("/all")
@Authorized(UserRole.Moderator)
public async getAllApplications(): Promise<readonly ApplicationDTO[]> {
const applications = await this._application.getAll();
return applications.map((application) =>
convertBetweenEntityAndDTO(application, ApplicationDTO),
);
}
/**
* Checks in the given user.
*/
@Put("/checkin")
@Authorized(UserRole.Moderator)
public async checkIn(@Body() { data: userID }: IDRequestDTO): Promise<void> {
const [user] = await this._users.findUsersByIDs([userID]);
if (user == null) {
throw new NotFoundError(`no user with id ${userID}`);
}
await this._application.checkIn(user);
}
/**
* Gets all existing teams.
*/
@Get("/team")
@Authorized(UserRole.User)
public async getAllTeams(): Promise<readonly TeamDTO[]> {
const teams = await this._teams.getAllTeams();
return teams.map((team) => convertBetweenEntityAndDTO(team, TeamDTO));
}
/**
* Creates a team.
*/
@Post("/team")
@Authorized(UserRole.User)
public async createTeam(
@Body() { data: teamDTO }: { data: TeamRequestDTO },
): Promise<TeamDTO> {
const team = convertBetweenEntityAndDTO(teamDTO, Team);
const createdTeam = await this._teams.createTeam(team);
return convertBetweenEntityAndDTO(createdTeam, TeamDTO);
}
/**
* Update a team.
*/
@Put("/team")
@Authorized(UserRole.User)
public async updateTeam(
@Body() { data: teamDTO }: { data: TeamUpdateDTO },
@CurrentUser() user: User,
): Promise<TeamDTO> {
const team = convertBetweenEntityAndDTO(teamDTO, Team);
const updateTeam = await this._teams.updateTeam(team, user);
return convertBetweenEntityAndDTO(updateTeam, TeamDTO);
}
/**
* Request to join a team.
* @param teamId The id of the team
*/
@Post("/team/:id/request")
@Authorized(UserRole.User)
public async requestToJoinTeam(
@Param("id") teamId: number,
@CurrentUser() user: User,
): Promise<SuccessResponseDTO> {
await this._teams.requestToJoinTeam(teamId, user);
const response = new SuccessResponseDTO();
response.success = true;
return response;
}
/**
* Accept a user to a team.
* @param teamId The id of the team
* @param userId The id of the user
*/
@Put("/team/:teamId/accept/:userId")
@Authorized(UserRole.User)
public async acceptUserToTeam(
@Param("teamId") teamId: number,
@Param("userId") userId: number,
@CurrentUser() user: User,
): Promise<SuccessResponseDTO> {
await this._teams.acceptUserToTeam(teamId, userId, user);
const response = new SuccessResponseDTO();
response.success = true;
return response;
}
/**
* Get team by id.
* @param id The id of the team
*/
@Get("/team/:id")
@Authorized(UserRole.User)
public async getTeamByID(
@Param("id") teamId: number,
): Promise<TeamResponseDTO> {
const team = await this._teams.getTeamByID(teamId);
if (team == null) {
throw new NotFoundError(`no team with id ${teamId}`);
}
return team;
}
/**
* Delete a team by id
* @param id The id of the team
*/
@Delete("/team/:id")
@Authorized(UserRole.User)
public async deleteTeamByID(
@Param("id") teamId: number,
@CurrentUser() user: User,
): Promise<SuccessResponseDTO> {
await this._teams.deleteTeamByID(teamId, user);
const response = new SuccessResponseDTO();
response.success = true;
return response;
}
}