-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathindex.ts
More file actions
665 lines (600 loc) · 16.5 KB
/
index.ts
File metadata and controls
665 lines (600 loc) · 16.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
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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
import {
getLoginToken,
isLoginTokenSet,
setLoginToken,
} from "../authentication";
import { Nullable } from "../util";
import type {
ApplicationController,
CriterionController,
ExtractControllerMethods,
IApiMethod,
IApiRequest,
IApiResponse,
ProjectsController,
RatingController,
SettingsController,
SystemController,
UsersController,
} from "./types/controllers";
import type {
AnswerDTO,
ApplicationDTO,
CriterionDTO,
FormDTO,
ProjectDTO,
ProjectRatingResultDTO,
RatingDTO,
SettingsDTO,
SuccessResponseDTO,
TeamDTO,
TeamResponseDTO,
UserDTO,
UserListDto,
} from "./types/dto";
type SettingsControllerMethods = ExtractControllerMethods<SettingsController>;
type UsersControllerMethods = ExtractControllerMethods<UsersController>;
type ApplicationControllerMethods =
ExtractControllerMethods<ApplicationController>;
type SystemControllerMethods = ExtractControllerMethods<SystemController>;
type CriterionControllerMethods = ExtractControllerMethods<CriterionController>;
type ProjectsControllerMethods = ExtractControllerMethods<ProjectsController>;
type RatingControllerMethods = ExtractControllerMethods<RatingController>;
type ExtractData<T> = T extends { data: infer K } ? K : never;
/**
* An api client connected to a backend. Stores the login token in `localStorage`.
*/
export class ApiClient {
private get headers(): Headers {
const headers = new Headers();
if (isLoginTokenSet()) {
headers.set("Authorization", `Bearer ${getLoginToken()}`);
}
return headers;
}
public constructor(private readonly _apiBaseUrl: string) {
if (!_apiBaseUrl) {
throw new Error("no API base url provided");
}
}
/**
* Packs the body in the api request structure.
* @param body The body to send
*/
private packApiRequest<TBody>(body: TBody): IApiRequest<TBody> {
return {
data: body,
};
}
/**
* Unpacks the body received from the api.
* @param body The body received from the api
*/
private unpackApiResponse<TBody>(body: IApiResponse<TBody>): TBody {
if (body.status === "ok") {
return body.data;
}
throw new Error(body.error);
}
/**
* Performs a request to the given url.
* @param url The resource to perform the request on
* @param method The method to use
* @param body An optional body to send with the request
*/
private async request<TControllerMethod extends IApiMethod<any, any>>(
url: string,
method: RequestInit["method"],
body?: ExtractData<TControllerMethod["takes"]>,
): Promise<ExtractData<TControllerMethod["returns"]>> {
const headers = this.headers;
const options: RequestInit = {
headers,
method,
};
if (body) {
headers.set("Content-Type", "application/json");
options.body = JSON.stringify(this.packApiRequest(body));
}
const response = await fetch(`${this._apiBaseUrl}${url}`, options);
return this.unpackApiResponse(await response.json());
}
/**
* Sends a GET request to the given resource.
* @param url The resource to get
*/
private async get<TControllerMethod extends IApiMethod<any, any>>(
url: string,
): Promise<ExtractData<TControllerMethod["returns"]>> {
return await this.request<TControllerMethod>(url, "get");
}
/**
* Sends a POST request to the given resource.
* @param url The resource to post
* @param body The body to send
*/
private async post<TControllerMethod extends IApiMethod<any, any>>(
url: string,
body: ExtractData<TControllerMethod["takes"]>,
): Promise<ExtractData<TControllerMethod["returns"]>> {
return await this.request<TControllerMethod>(url, "post", body);
}
/**
* Sends a PUT request to the given resource.
* @param url The resource to put
* @param body The body to send
*/
private async put<TControllerMethod extends IApiMethod<any, any>>(
url: string,
body: ExtractData<TControllerMethod["takes"]>,
): Promise<ExtractData<TControllerMethod["returns"]>> {
return await this.request<TControllerMethod>(url, "put", body);
}
/**
* Sends a DELETE request to the given resource.
* @param url The resource to delete
*/
private async delete<TControllerMethod extends IApiMethod<any, any>>(
url: string,
): Promise<ExtractData<TControllerMethod["returns"]>> {
return await this.request<TControllerMethod>(url, "delete");
}
/**
* Attempts to revive a stringified date to an actual `Date` object.
* @param date The date to revive
*/
private reviveDate<T extends Date | Nullable<Date>>(date: T): T {
if (date == null) {
return null as T;
}
return new Date(date as any) as T;
}
/**
* Revives dates in the settings object.
* @param settings The settings to revive
*/
private reviveSettings(settings: SettingsDTO): SettingsDTO {
return {
...settings,
application: {
...settings.application,
allowProfileFormFrom: this.reviveDate(
settings.application.allowProfileFormFrom,
),
allowProfileFormUntil: this.reviveDate(
settings.application.allowProfileFormUntil,
),
acceptanceDeadline: this.reviveDate(
settings.application.acceptanceDeadline,
),
confirmSpotUntil: this.reviveDate(
settings.application.confirmSpotUntil,
),
},
};
}
/**
* Revievs dates in the given user object.
* @param user The user to revive
*/
private reviveUser(user: UserDTO): UserDTO {
return {
...user,
confirmationExpiresAt: this.reviveDate(user.confirmationExpiresAt),
createdAt: this.reviveDate(user.createdAt),
initialProfileFormSubmittedAt: this.reviveDate(
user.initialProfileFormSubmittedAt,
),
};
}
/**
* Sends a settings api request.
*/
public async getSettings(): Promise<SettingsDTO> {
const response = await this.get<SettingsControllerMethods["getSettings"]>(
"/settings",
);
return this.reviveSettings(response);
}
/**
* Sends a signup api request.
* @param email The user's email
* @param password The user's password
*/
public async signup(
firstName: string,
lastName: string,
email: string,
password: string,
): Promise<string> {
const response = await this.post<UsersControllerMethods["signup"]>(
"/user/signup",
{
firstName,
lastName,
email,
password,
},
);
return response.email;
}
/**
* Create a new team
* @param title The team's title
* @param description The team's description
* @param teamImg The team's image
* @param users The team's users
*/
public async createTeam(
title: string,
description: string,
teamImg: string,
users: number[],
): Promise<void> {
await this.post<ApplicationControllerMethods["createTeam"]>(
"/application/team",
{
title,
users,
teamImg,
description,
},
);
}
/**
* Update new team
* @param id The team's id
* @param title The team's title
* @param description The team's description
* @param teamImg The team's image
* @param users The team's users
*/
public async updateTeam(
id: number,
title: string,
description: string,
teamImg: string,
users: number[],
): Promise<void> {
await this.put<ApplicationControllerMethods["updateTeam"]>(
"/application/team",
{
id,
title,
users,
teamImg,
description,
},
);
}
/**
* Request to join a team
* @param teamId The team's id
* @param userId The user's id
*/
public async requestToJoinTeam(teamId: number): Promise<void> {
await this.post<ApplicationControllerMethods["requestToJoinTeam"]>(
`/application/team/${teamId}/request`,
{} as never,
);
}
/**
* Accept a user to a team
* @param teamId The team's id
* @param userId The user's id
*/
public async acceptUserToTeam(teamId: number, userId: number): Promise<void> {
await this.put<ApplicationControllerMethods["acceptUserToTeam"]>(
`/application/team/${teamId}/accept/${userId}`,
{} as never,
);
}
/**
* Delete a team by id
* @param id The team's id
*/
public async deleteTeam(id: number): Promise<void> {
await this.delete<ApplicationControllerMethods["deleteTeamByID"]>(
`/application/team/${id}`,
);
}
/**
* Forgot password
* @param email The user's email
*/
public async forgotPassword(email: string): Promise<string> {
const response = await this.post<UsersControllerMethods["forgotPassword"]>(
"/user/forgot-password",
{
email,
},
);
return response.message;
}
/**
* Reset password
* @param password The new user's password
* @param token The reset token
*/
public async resetPassword(
password: string,
token: string,
): Promise<boolean> {
const response = await this.post<UsersControllerMethods["resetPassword"]>(
"/user/reset-password",
{
password,
token,
},
);
return response.success;
}
/**
* Verifies a user's email address.
* @param token The email verification token
*/
public async verifyEmail(token: string): Promise<void> {
await this.get<UsersControllerMethods["verify"]>(
`/user/verify?token=${token}`,
);
}
/**
* Logs a user in and gets the user's status.
* @param email The user's email
* @param password The user's password
*/
public async login(email: string, password: string): Promise<UserDTO> {
const response = await this.post<UsersControllerMethods["login"]>(
"/user/login",
{
email,
password,
},
);
setLoginToken(response.token);
return this.reviveUser(response.user);
}
/**
* Refreshes the login token and returns the current user status.
*/
public async refreshLoginToken(): Promise<UserDTO> {
const response = await this.get<
UsersControllerMethods["refreshLoginToken"]
>("/user/refreshtoken");
setLoginToken(response.token);
return this.reviveUser(response.user);
}
/**
* Updates the settings.
* @param settings The settings to use for updating
*/
public async updateSettings(settings: SettingsDTO): Promise<SettingsDTO> {
const response = await this.put<
SettingsControllerMethods["updateSettings"]
>("/settings", settings);
return this.reviveSettings(response);
}
/**
* Gets the profile form for the current user.
*/
public async getProfileForm(): Promise<FormDTO> {
return await this.get<ApplicationControllerMethods["getProfileForm"]>(
"/application/profile",
);
}
/**
* Stores the answers to the profile form.
* @param answers The given answers
*/
public async storeProfileFormAnswers(
answers: readonly AnswerDTO[],
): Promise<void> {
return await this.post<
ApplicationControllerMethods["storeProfileFormAnswers"]
>("/application/profile", answers);
}
/**
* Admits the given users.
* @param userIDs The users to admit
*/
public async admit(userIDs: readonly number[]): Promise<void> {
return await this.put<ApplicationControllerMethods["admit"]>(
"/application/admit",
userIDs,
);
}
/**
* Gets the confirmation form for the current user.
*/
public async getConfirmationForm(): Promise<FormDTO> {
return await this.get<ApplicationControllerMethods["getConfirmationForm"]>(
"/application/confirm",
);
}
/**
* Stores the answers to the confirmation form.
* @param answers The given answers
*/
public async storeConfirmationFormAnswers(
answers: readonly AnswerDTO[],
): Promise<void> {
return await this.post<
ApplicationControllerMethods["storeConfirmationFormAnswers"]
>("/application/confirm", answers);
}
/**
* Gets all applications with users and their answers.
*/
public async getAllApplications(): Promise<readonly ApplicationDTO[]> {
const response = await this.get<
ApplicationControllerMethods["getAllApplications"]
>("/application/all");
return response.map((application) => ({
...application,
user: this.reviveUser(application.user),
}));
}
/**
* Get all teams
* @returns all teams
*/
public async getAllTeams(): Promise<readonly TeamDTO[]> {
return await this.get<ApplicationControllerMethods["getAllTeams"]>(
"/application/team",
);
}
/**
* Get Team by Id
* @return team by id
*/
public async getTeamByID(id: number): Promise<TeamResponseDTO> {
return await this.get<ApplicationControllerMethods["getTeamByID"]>(
`/application/team/${id}`,
);
}
/**
* Get all users
* @returns all users
*/
public async getAllUsers(): Promise<readonly UserListDto[]> {
return await this.get<UsersControllerMethods["getUserList"]>("/user/list");
}
/**
* Deletes the user with the given id.
* @param userID The id of the user to delete
*/
public async deleteUser(userID: number): Promise<void> {
await this.delete<UsersControllerMethods["deleteUser"]>(`/user/${userID}`);
}
/**
* Declines the user's spot.
*/
public async declineSpot(): Promise<void> {
await this.delete<ApplicationControllerMethods["declineSpot"]>(
"/application/confirm",
);
}
/**
* Checks in the given user.
* @param userID The id of the user to check in
*/
public async checkIn(userID: number): Promise<void> {
await this.put<ApplicationControllerMethods["checkIn"]>(
"/application/checkin",
userID,
);
}
/**
* Prunes all system data.
*/
public async pruneSystem(): Promise<void> {
await this.delete<SystemControllerMethods["prune"]>("/system/prune");
}
// Criteria
/**
* Gets all criteria.
*/
public async getAllCriteria(): Promise<readonly CriterionDTO[]> {
return await this.get<CriterionControllerMethods["getAllCriteria"]>(
"/criteria",
);
}
/**
* Creates a new criterion.
* @param criteria The criterion to create
*/
public async createCriterion(criterion: CriterionDTO): Promise<CriterionDTO> {
return await this.post<CriterionControllerMethods["createCriterion"]>(
"/criteria",
criterion,
);
}
/**
* Updates a criterion.
* @param id The id of the criterion to update
* @param criteria The updated criterion data
*/
public async updateCriterion(
id: number,
criterion: CriterionDTO,
): Promise<CriterionDTO> {
return await this.put<
IApiMethod<
{ data: CriterionDTO },
CriterionControllerMethods["updateCriterion"]["returns"]
>
>(`/criteria/${id}`, criterion);
}
/**
* Deletes a criterion by id.
* @param id The id of the criterion to delete
*/
public async deleteCriterion(id: number): Promise<SuccessResponseDTO> {
return await this.delete<CriterionControllerMethods["deleteCriterion"]>(
`/criteria/${id}`,
);
}
// Projects
/**
* Get Project by Id
* @return project by id
*/
public async getProjectByID(id: number): Promise<ProjectDTO> {
return await this.get<ProjectsControllerMethods["getProjectByID"]>(
`/projects/${id}`,
);
}
/**
* Gets all projects.
*/
public async getAllProjects(): Promise<readonly ProjectDTO[]> {
return await this.get<ProjectsControllerMethods["getAllProjects"]>(
"/projects",
);
}
/**
* Updates a project.
* @param id The id of the project to update
* @param project The updated project data
*/
public async updateProject(
id: number,
project: ProjectDTO,
): Promise<ProjectDTO> {
return await this.put<
IApiMethod<
{ data: ProjectDTO },
ProjectsControllerMethods["updateProject"]["returns"]
>
>(`/projects/${id}`, project);
}
// Ratings
/**
* Gets all ratings.
*/
public async getUsersRatingsForProject(
project: ProjectDTO,
): Promise<readonly RatingDTO[]> {
return await this.get<RatingControllerMethods["getUsersRatingsForProject"]>(
`/ratings/by-project/${project.id}`,
);
}
/**
* Gets aggregated rating results grouped by project and criteria.
*/
public async getRatingResults(): Promise<readonly ProjectRatingResultDTO[]> {
return await this.get<RatingControllerMethods["getRatingResults"]>(
"/ratings/results",
);
}
/**
* Submits a rating for a project.
* @param rating The rating to submit
*/
public async createRating(rating: RatingDTO): Promise<RatingDTO> {
return await this.post<RatingControllerMethods["rate"]>(
"/ratings/rate",
rating,
);
}
}