-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.ts
131 lines (104 loc) · 2.79 KB
/
index.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 { Lotto, Router } from '../src'
const users = [
{
id: 1,
name: 'Mario',
surname: 'Rossi',
},
{
id: 2,
name: 'Max',
surname: 'Mustermann',
},
{
id: 3,
name: 'Jane',
surname: 'Doe',
},
{
id: 4,
name: 'Pera',
surname: 'Perić',
},
]
const profiles = [
{ id: 1, userId: 1, sex: 'male', nationality: 'Italian' },
{ id: 2, userId: 2, sex: 'male', nationality: 'Austrian' },
{ id: 3, userId: 3, sex: 'female', nationality: 'American' },
{ id: 4, userId: 4, sex: 'female', nationality: 'Serbian' },
]
const lottoJS = new Lotto({
host: '0.0.0.0',
port: 9004,
prefix: '/api',
})
// Auth middleware
lottoJS.use(({ req, res, next }) => {
if (req.headers.authorization !== '1234') {
return res.status(401).json({ message: 'unauthorized.' })
}
next()
})
lottoJS.get('/', ({ res }) => {
return res.status(200).text('welcome!')
})
const lottoRouter = new Router()
lottoRouter.get('/', ({ req, res }) => {
const { name } = req.query
if (!name) return res.status(200).json(users)
const searchUsers = users.filter((user) => user.name === name)
if (!searchUsers) {
return res.status(404).json({
message: 'user not found.',
})
}
return res.status(200).json(searchUsers)
})
lottoRouter.get('/:id', ({ req, res }) => {
const userId = Number(req.param('id'))
const showFullInfo = req.get('full')
const user = users.find((user) => user.id === userId)
if (!user) {
return res.status(404).json({
message: 'user not found.',
})
}
if (!showFullInfo) return res.status(200).json(user)
const profile = profiles.find((profile) => profile.userId === userId)
return res.status(200).json({
...user,
...(profile
? {
profile: {
sex: profile.sex,
nationality: profile.nationality,
},
}
: {}),
})
})
lottoRouter.put('/:id', ({ req, res }) => {
const { id } = req.params
const body = req.body
const user = users.find((user) => user.id === Number(id))
if (!user) {
return res.status(404).json({
message: 'user not found.',
})
}
const profile = profiles.find((profile) => profile.userId === Number(id))
if (!profile)
return res.status(404).json({
message: 'profile not found.',
})
user.name = body.name
user.surname = body.name
profile.sex = body.profile.sex
profile.nationality = body.profile.nationality
return res.status(201).json({
...user,
...profile,
})
})
lottoJS.use('users', lottoRouter)
lottoJS.init()