forked from chrispsheehan/simple-mock
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathusers.ts
67 lines (49 loc) · 1.48 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
import { createGuid } from "./helper";
import { Request, Response } from 'express';
const usersExist = (state: any): boolean => {
try {
if(Array.isArray(state.users)) {
return true;
}
} catch (error) {
console.warn('user object not found')
return false;
}
}
const getUsers = (req: Request, res: Response) => {
let userid = req.query.userid;
if(!usersExist(state.data)) {
res.status(200).json({
users: []
});
}
else {
if(userid) {
let user = global.state.data.users.filter(user => user.id === userid)
res.status(200).json(user[0]);
}
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: { firstName: string; lastName: string; }) => 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);
}
}
export default {
getUsers,
postUser
};