Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
445 lines (373 loc) · 12.3 KB
/
Copy pathserver.js
File metadata and controls
445 lines (373 loc) · 12.3 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
import jsonServer from "json-server";
const server = jsonServer.create();
const router = jsonServer.router("db.json");
const middlewares = jsonServer.defaults();
server.use(middlewares);
server.use(jsonServer.bodyParser);
server.use((req, res, next) => {
const db = router.db;
const { method, path } = req;
console.log(`General Middleware Check: ${req.method} ${req.url}`);
console.log(`Incoming request: ${req.method} ${req.path}`);
console.log(`Path segments:`, req.path.split("/"));
// GET Fetching users by project
if (method === "GET" && path.match(/\/projects\/\d+\/users/)) {
const projectId = parseInt(path.split("/")[2], 10);
const project = db.get("projects").find({ id: projectId }).value();
if (!project) {
res.status(404).json({ error: "Project not found" });
return;
}
const allUsers = db.get("users").value();
const projectUsers = Object.values(project.access).flat();
let allProjectUsers = allUsers
.filter((user) => projectUsers.includes(user.id))
.map((user) => ({
id: user.id,
username: user.username,
role: Object.keys(project.access).find((role) =>
project.access[role].includes(user.id)
),
}));
res.json({ allProjectUsers });
return;
}
// POST Adding a new user
if (method === "POST" && path === "/users") {
const { username } = req.body;
if (!username) {
res.status(400).json({ error: "Username is required" });
return;
}
const user = db.get("users").find({ username }).value();
if (user) {
res.status(400).json({ error: "Username already exists" });
return;
}
const newUser = db.get("users").insert({ username }).write();
res.json({ message: "User added successfully", user: newUser });
return;
}
// PUT Assigning tasks to users
if (
method === "PUT" &&
/\/projects\/(\d+)\/tasks\/(\d+)\/assign/.test(path)
) {
const [, projectId, taskId] = path.match(
/\/projects\/(\d+)\/tasks\/(\d+)\/assign/
);
const userId = req.body.userId ? parseInt(req.body.userId) : null;
const project = db
.get("projects")
.find({ id: Number(projectId) })
.value();
if (!project) {
res.status(404).json({ error: "Project not found" });
return;
}
const taskIndex = project.tasks.findIndex((t) => t.id === Number(taskId));
if (taskIndex === -1) {
res.status(404).json({ error: "Task not found" });
return;
}
project.tasks[taskIndex].assignee = userId
? { userId: Number(userId) }
: { userId: null };
db.get("projects")
.find({ id: Number(projectId) })
.assign({ tasks: project.tasks })
.write();
res.json({ message: "Task assigned successfully", project });
return;
}
// GET Removing task assignment
if (method === "GET" && path.includes("/projects-by-user/")) {
const userId = parseInt(req.path.split("/")[2]);
console.log(`Fetching projects for user ID: ${userId}`);
const projects = db.get("projects").value();
const accessibleProjects = projects.filter((project) =>
Object.values(project.access).some((role) => role.includes(userId))
);
console.log(`Accessible projects: ${JSON.stringify(accessibleProjects)}`);
if (accessibleProjects.length > 0) {
res.json(accessibleProjects);
} else {
res.status(404).json({ error: "No projects found for this user" });
}
return;
}
// GET Fetching eligible users for a task
if (
method === "GET" &&
path.match(/\/projects\/\d+\/tasks\/\d+\/eligible-users/)
) {
const projectId = parseInt(path.split("/")[2], 10);
const taskId = parseInt(path.split("/")[4], 10);
const project = db.get("projects").find({ id: projectId }).value();
if (!project) {
res.status(404).json({ error: "Project not found" });
return;
}
const task = project.tasks.find((t) => t.id === taskId);
if (!task) {
res.status(404).json({ error: "Task not found" });
return;
}
const allUsers = db.get("users").value();
const projectUsers = Object.values(project.access).flat();
let eligibleUsers = allUsers.filter((user) =>
projectUsers.includes(user.id)
);
console.log(
`Eligible users: ${JSON.stringify(
eligibleUsers
)} and assignee: ${JSON.stringify(task.assignee)}`
);
res.json({ eligibleUsers, assignee: task.assignee });
return;
}
// GET Fetching eligible users not in the project with optional search query
if (method === "GET" && path.match(/\/users\/search/)) {
const projectId = parseInt(req.query.projectId, 10);
const query = req.query.query
? req.query.query
.trim()
.toLowerCase()
.replace(/[^a-z0-9]/g, "")
: "";
console.log(`Received projectId: ${projectId}`);
console.log(`Received search query: ${query}`);
const project = db.get("projects").find({ id: projectId }).value();
if (!project) {
res.status(404).json({ error: "Project not found" });
return;
}
const allUsers = db.get("users").value();
const projectUsers = Object.values(project.access).flat();
console.log(`Project users: ${JSON.stringify(projectUsers)}`);
let eligibleUsers = allUsers
.filter((user) => !projectUsers.includes(user.id))
.map(({ id, username }) => ({ id, username }));
console.log(
`Eligible users before filtering by query: ${JSON.stringify(
eligibleUsers
)}`
);
if (query) {
eligibleUsers = eligibleUsers.filter((user) =>
user.username.toLowerCase().includes(query)
);
}
console.log(
`Eligible users after filtering by query: ${JSON.stringify(
eligibleUsers
)}`
);
res.json({ eligibleUsers });
return;
}
// POST Adding a user to a project
if (method === "POST" && path.match(/^\/projects\/(\d+)\/access\/(\w+)$/)) {
const projectId = parseInt(path.split("/")[2], 10);
const role = path.split("/")[4];
const userId = parseInt(req.body.userId);
const project = db.get("projects").find({ id: projectId }).value();
if (!project) {
res.status(404).json({ error: "Project not found" });
return;
}
if (!userId) {
res.status(400).json({ error: "User ID is required" });
return;
}
if (!project.access[role]) {
res.status(400).json({ error: "Role does not exist" });
return;
}
if (project.access[role].includes(userId)) {
res.status(400).json({ error: "User already has access" });
return;
}
project.access[role].push(userId);
db.get("projects")
.find({ id: projectId })
.assign({ access: project.access })
.write();
console.log(`User added to project: ${JSON.stringify(project)}`);
res.json({ message: "User added successfully", project });
return;
}
// DELETE Removing a user from a project access
if (method === "DELETE" && path.match(/^\/projects\/(\d+)\/access\/(\d+)$/)) {
const projectId = parseInt(path.split("/")[2], 10);
const userId = parseInt(path.split("/")[4], 10);
const project = db.get("projects").find({ id: projectId }).value();
if (!project) {
res.status(404).json({ error: "Project not found" });
return;
}
let found = false; // Flag to check if the user was found in any role
Object.keys(project.access).forEach((role) => {
if (project.access[role].includes(userId)) {
project.access[role] = project.access[role].filter(
(id) => id !== userId
);
found = true;
}
});
if (!found) {
res
.status(400)
.json({ error: "User does not have access to this project" });
return;
}
db.get("projects")
.find({ id: projectId })
.assign({ access: project.access })
.write();
res.json({ message: "User removed successfully from all roles", project });
return;
}
// POST Create a new project
if (method === "POST" && path === "/projects") {
const { name, description, date, userChanges, globalUserId } = req.body;
const access = {
admin: [],
editor: [],
reader: [],
};
// Process added users
userChanges.addedUsers.forEach((user) => {
if (!access[user.role]) {
access[user.role] = [];
}
access[user.role].push(user.userId);
});
const newProject = db
.get("projects")
.insert({
name,
description,
date,
access: {
...access,
admin: access.admin
? [...access.admin, globalUserId]
: [globalUserId],
},
tasks: [],
})
.write();
res
.status(201)
.json({ message: "Project created successfully", project: newProject });
return;
}
// PUT endpoint for updating an existing project
if (method === "PUT" && path.match(/^\/projects\/(\d+)$/)) {
const projectId = parseInt(path.split("/")[2], 10);
const { name, description, date, userChanges } = req.body;
let project = db.get("projects").find({ id: projectId }).value();
if (!project) {
return res.status(404).json({ error: "Project not found" });
}
// Update project details
project.name = name;
project.description = description;
project.date = date;
// Process user changes to update access
const access = project.access || {
admin: [],
editor: [],
reader: [],
};
// Process added users
userChanges.addedUsers.forEach((user) => {
if (!access[user.role]) {
access[user.role] = [];
}
if (!access[user.role].includes(user.userId)) {
access[user.role].push(user.userId);
}
});
// Process removed users
userChanges.removedUsers.forEach((user) => {
Object.keys(access).forEach((role) => {
access[role] = access[role].filter((id) => id !== user.userId);
});
});
project.access = access;
db.get("projects").find({ id: projectId }).assign(project).write();
res.json({ message: "Project updated successfully", project });
return;
}
// DELETE remove a project
if (method === "DELETE" && path.match(/^\/projects\/\d+$/)) {
const projectId = parseInt(path.split("/")[2], 10);
const project = db.get("projects").find({ id: projectId }).value();
if (!project) {
res.status(404).json({ error: "Project not found" });
return;
}
db.get("projects").remove({ id: projectId }).write();
res.json({ message: "Project removed successfully" });
return;
}
// POST Adding a task to a project
if (method === "POST" && path.match(/^\/projects\/\d+\/tasks$/)) {
const projectId = parseInt(path.split("/")[2], 10);
const { description } = req.body;
const project = db.get("projects").find({ id: projectId }).value();
if (!project) {
res.status(404).json({ error: "Project not found" });
return;
}
console.log(
`Adding task to project: ${projectId} with description: ${description}`
);
const newTask = db
.get("projects")
.find({ id: projectId })
.get("tasks")
.insert({
description,
assignee: {
userId: null,
},
})
.write();
res.status(201).json({ message: "Task added successfully", task: newTask });
return;
}
// DELETE Removing a task from a project
if (method === "DELETE" && path.match(/^\/projects\/\d+\/tasks\/\d+$/)) {
const [, projectId, taskId] = path.match(/\/projects\/(\d+)\/tasks\/(\d+)/);
const project = db
.get("projects")
.find({ id: Number(projectId) })
.value();
if (!project) {
res.status(404).json({ error: "Project not found" });
return;
}
const taskIndex = project.tasks.findIndex((t) => t.id === Number(taskId));
if (taskIndex === -1) {
res.status(404).json({ error: "Task not found" });
return;
}
project.tasks.splice(taskIndex, 1);
db.get("projects")
.find({ id: Number(projectId) })
.assign({ tasks: project.tasks })
.write();
res.json({ message: "Task removed successfully", project });
return;
}
console.log(`Final catch-all middleware: ${req.method} ${req.path}`);
next();
});
server.use(router);
const port = 3001;
server.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});