-
Notifications
You must be signed in to change notification settings - Fork 1
/
users.ts
131 lines (90 loc) · 2.51 KB
/
users.ts
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
import { createGuid } from "./helper";
import { Request, Response } from 'express';
interface User {
id: string,
firstName: string,
lastName: string
}
function usersExist(state: any): boolean {
try {
if (Array.isArray(state.users)) {
return true;
}
} catch (error) {
console.warn('user object not found');
return false;
}
}
function selectUser(req: Request): User[] {
const { userid } = req.params;
return global.state.data.users.filter((user: User) => user.id === userid);
}
function addUser(res: Response, newUser: User) {
global.state.data.users.map((user: User) => [newUser].find((u: User) => u.id === user.id) || user);
return res.status(200).json(newUser);
}
function userNotFoundResponse(res: Response) {
return res.status(400).json({ badrequest: "User not found" });
}
const getUser = (req: Request, res: Response) => {
let user = selectUser(req);
if(user.length) {
res.status(200).json(user[0]);
}
else {
userNotFoundResponse(res);
}
}
const getUsers = (req: Request, res: Response) => {
if(!usersExist(state.data)) {
res.status(200).json({
users: []
});
}
else {
res.status(200).json(global.state.data.users);
}
}
const postUser = (req: Request, res: Response) => {
let newUser = req.body;
if(!usersExist(global.state.data)) { // create users if not there
global.state.data = {
users: []
}
}
if (global.state.data.users.filter((user: User) => user.firstName === newUser.firstName && user.lastName === newUser.lastName).length > 0) {
res.status(400).json({ badrequest: "User already exists" });
}
else {
let savedUser = {...newUser, ...{id: createGuid()}}
global.state.data.users.push(savedUser);
res.status(201).json(savedUser);
}
}
const putUser = (req: Request, res: Response) => {
const newUser: User = req.body;
let user = selectUser(req);
if(user.length) {
addUser(res, newUser);
}
else {
userNotFoundResponse(res);
}
}
const patchUser = (req: Request, res: Response) => {
let user = selectUser(req);
if(user.length) {
const newUser: User = Object.assign(user[0], req.body);
addUser(res, newUser);
}
else {
userNotFoundResponse(res);
}
}
export default {
getUser,
getUsers,
postUser,
putUser,
patchUser
};