-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApiService.ts
More file actions
378 lines (342 loc) · 9.66 KB
/
ApiService.ts
File metadata and controls
378 lines (342 loc) · 9.66 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
import { GetStudentsResponse, User } from "@/service/types/usernator";
import ApiError from "@/service/types/error";
import getConfig from "next/config";
import {
Assignment,
AssignmentLanguage,
AssignmentsResponse,
Group,
GroupJoinRequest,
GroupJoinRequestResponse,
GroupsResponse,
MongoTestFile,
QuestionCatalogueElement,
QuestionSolution,
RunnerConfig,
Solution,
SolutionFilesResponse,
SolutionsResponse,
} from "@/service/types/tasky";
import { FileStructureTree } from "@/components/FileStructure";
export interface GenericMessage {
message: string;
}
class ApiService {
private apiUrl: string;
constructor() {
//this.apiUrl = process.env.NODE_ENV === "production" ? "https://api.code-canvas.app" : "http://localhost:3002";
this.apiUrl = getConfig().publicRuntimeConfig.API_URL
? getConfig().publicRuntimeConfig.API_URL
: "http://localhost:3001";
}
public async self(): Promise<User | string> {
return await this.get<User>("/usernator/self");
}
public async registerUser(username: string, password: string): Promise<User> {
return await this.post<User>("/usernator/register", { username, password });
}
public async loginUser(
username: string,
password: string,
): Promise<GenericMessage> {
return await this.post<GenericMessage>("/usernator/login", {
username,
password,
});
}
public async getStudents(): Promise<GetStudentsResponse> {
return await this.get<GetStudentsResponse>("/usernator/all-students");
}
public async createGroup(title: string): Promise<Group> {
return await this.post<Group>(`/tasky/create_group`, { title });
}
public async getGroups(): Promise<GroupsResponse> {
return await this.get<GroupsResponse>("/tasky/groups");
}
public async getMyGroups(): Promise<GroupsResponse> {
return await this.get<GroupsResponse>("/tasky/my_groups");
}
public async getGroup(id: number): Promise<Group> {
return await this.get<Group>("/tasky/groups/" + id);
}
public async getGroupJoinRequests(
id: number,
): Promise<GroupJoinRequestResponse> {
return await this.get<GroupJoinRequestResponse>(
`/tasky/groups/${id}/join_requests`,
);
}
public async createGroupJoinRequest(id: number): Promise<GroupJoinRequest> {
return await this.post<GroupJoinRequest>(
`/tasky/groups/${id}/create_join_request`,
{},
);
}
public async approveGroupJoinRequest(
groupId: number,
id: number,
): Promise<Group> {
return await this.post<Group>(
`/tasky/groups/${groupId}/join_requests/${id}/approve`,
{},
);
}
public async rejectGroupJoinRequest(
groupId: number,
id: number,
): Promise<Group> {
return await this.post<Group>(
`/tasky/groups/${groupId}/join_requests/${id}/reject`,
{},
);
}
public async createAssignment(
groupId: number,
title: string,
due_date: Date,
description: string,
language: AssignmentLanguage,
): Promise<Assignment> {
return await this.post<Assignment>(`/tasky/groups/${groupId}/assignments`, {
title,
due_date,
description,
language,
});
}
public async getAssignmentsForGroup(
id: number,
): Promise<AssignmentsResponse> {
return await this.get<AssignmentsResponse>(
`/tasky/groups/${id}/assignments`,
);
}
public async getAssignmentForGroup(
groupId: number,
assignmentId: number,
): Promise<Assignment> {
return await this.get<Assignment>(
`/tasky/groups/${groupId}/assignments/${assignmentId}`,
);
}
public async updateAssignment(
groupId: number,
assignmentId: number,
title: string,
due_date: Date,
description: string,
): Promise<Assignment> {
return await this.post<Assignment>(
`/tasky/groups/${groupId}/assignments/${assignmentId}/update`,
{ title, due_date, description },
);
}
public async getCodeTestsFiles(
groupId: number,
assignmentId: number,
fileIds: string[],
): Promise<MongoTestFile[]> {
return await this.get<MongoTestFile[]>(
`/tasky/groups/${groupId}/assignments/${assignmentId}/code_test_files?object_ids=${fileIds.join(",")}`,
);
}
public async getPersonalSolutions(): Promise<SolutionsResponse> {
return await this.get<SolutionsResponse>("/tasky/personal_solutions");
}
public async getSolution(id: number): Promise<Solution> {
return await this.get<Solution>(`/tasky/solutions/${id}`);
}
public async getSolutionFiles(
id: number,
testFiles: string[],
taskFiles: string[],
): Promise<SolutionFilesResponse> {
return await this.get<SolutionFilesResponse>(
`/tasky/solutions/${id}/files?task_files=${taskFiles.join(",")}&test_files=${testFiles.join(",")}`,
);
}
public async getSolutionsForAssignment(
id: number,
): Promise<SolutionsResponse> {
return await this.get<SolutionsResponse>(
`/tasky/assignments/${id}/solutions`,
);
}
public async approveSolution(id: number): Promise<Solution> {
return await this.post<Solution>(`/tasky/solutions/${id}/approve`, {});
}
public async rejectSolution(id: number): Promise<Solution> {
return await this.post<Solution>(`/tasky/solutions/${id}/reject`, {});
}
public async createQuestionCatalogue(
groupId: number,
assignmentId: number,
questions: QuestionCatalogueElement[],
): Promise<Assignment> {
return await this.post<Assignment>(
`/tasky/groups/${groupId}/assignments/${assignmentId}/question_catalogue`,
{ questions },
);
}
public async createCodeTests(
groupId: number,
assignmentId: number,
fileStructure: FileStructureTree,
files: File[],
runnerConfig: RunnerConfig,
): Promise<Assignment> {
try {
const formData = new FormData();
formData.set(
"file_structure",
new Blob([JSON.stringify(fileStructure)], { type: "application/json" }),
);
for (const file of files) {
formData.append("files", file, file.name);
}
formData.set(
"runner_config",
new Blob([JSON.stringify(runnerConfig)], { type: "application/json" }),
);
const resp = await fetch(
`${this.apiUrl}/tasky/groups/${groupId}/assignments/${assignmentId}/code_test`,
{
method: "POST",
mode: "cors",
body: formData,
credentials: "include",
headers: {
Accept: "application/json",
},
},
);
const txt = await resp.text();
const obj = this.getObject(txt);
if (resp.status !== 200) {
throw new ApiError(resp.status, obj.message);
}
return obj;
} catch (e) {
if (e instanceof Error) {
throw new ApiError(-1, e.message);
}
throw new ApiError(-1, `${e}`);
}
}
public async createSolution(
assignmentId: number,
files: File[],
answers: Map<string, QuestionSolution> | undefined = undefined,
): Promise<Solution> {
try {
const formData = new FormData();
for (const file of files) {
formData.append("files", file, file.name);
}
if (answers !== undefined) {
formData.set(
"answers",
new Blob([JSON.stringify(Object.fromEntries(answers.entries()))], {
type: "application/json",
}),
);
} else {
formData.set(
"answers",
new Blob(["{}"], {
type: "application/json",
}),
);
}
const resp = await fetch(
`${this.apiUrl}/tasky/assignments/${assignmentId}/solutions`,
{
method: "POST",
mode: "cors",
body: formData,
credentials: "include",
headers: {
Accept: "application/json",
},
},
);
const txt = await resp.text();
const obj = this.getObject(txt);
if (resp.status !== 200) {
throw new ApiError(resp.status, obj.message);
}
return obj;
} catch (e) {
if (e instanceof Error) {
throw new ApiError(-1, e.message);
}
throw new ApiError(-1, `${e}`);
}
}
/**
* Executes a general get request
*
* @param path The path
* @throws ApiError The api error
* @private
*/
private async get<T>(path: string): Promise<T> {
return await this.fetch<T>(path, "GET", undefined);
}
/**
* Executes a general post request
*
* @param path The path
* @param body The json body
* @throws ApiError The api error
* @private
*/
private async post<T>(path: string, body: object): Promise<T> {
return await this.fetch<T>(path, "POST", body);
}
/**
* Executes a generic HTTP fetch
*
* @param path The path
* @param method The method
* @param body The body if exists
* @private
*/
private async fetch<T>(
path: string,
method: string,
body?: object,
): Promise<T> {
try {
const resp = await fetch(`${this.apiUrl}${path}`, {
method,
mode: "cors",
body: body ? JSON.stringify(body) : undefined,
credentials: "include",
headers: {
"Content-Type": "application/json",
Accept: "*/*",
},
});
const txt = await resp.text();
const obj = this.getObject(txt);
if (resp.status !== 200) {
throw new ApiError(resp.status, obj.message);
}
return obj as T;
} catch (e) {
if (e instanceof Error) {
throw new ApiError(-1, e.message);
}
throw new ApiError(-1, `${e}`);
}
}
private getObject(text: string): any | GenericMessage {
try {
return JSON.parse(text);
} catch (_) {
return { message: text } as GenericMessage;
}
}
}
export default ApiService;