-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
server-handlers.js
181 lines (161 loc) · 5.17 KB
/
server-handlers.js
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
import {rest} from 'msw'
import * as booksDB from './data/books'
import * as usersDB from './data/users'
import * as listItemsDB from './data/list-items'
let sleep
if (process.env.NODE_ENV === 'test') {
sleep = () => Promise.resolve()
} else {
sleep = (
t = Math.random() * ls('__bookshelf_variable_request_time__', 400) +
ls('__bookshelf_min_request_time__', 400),
) => new Promise(resolve => setTimeout(resolve, t))
}
function ls(key, defaultVal) {
const lsVal = window.localStorage.getItem(key)
let val
if (lsVal) {
val = Number(val)
}
return Number.isFinite(val) ? val : defaultVal
}
const apiUrl = process.env.REACT_APP_API_URL
const handlers = [
rest.get(`${apiUrl}/me`, async (req, res, ctx) => {
const user = getUser(req)
return res(ctx.json({user}))
}),
rest.post(`${apiUrl}/login`, async (req, res, ctx) => {
const {username, password} = req.body
const user = usersDB.authenticate({username, password})
return res(ctx.json({user}))
}),
rest.post(`${apiUrl}/register`, async (req, res, ctx) => {
const {username, password} = req.body
const userFields = {username, password}
usersDB.create(userFields)
let user
try {
user = usersDB.authenticate(userFields)
} catch (error) {
return res(ctx.status(400), ctx.json({message: error.message}))
}
return res(ctx.json({user}))
}),
rest.get(`${apiUrl}/books`, async (req, res, ctx) => {
if (!req.query.has('query')) {
return ctx.fetch(req)
}
const query = req.query.get('query')
let matchingBooks = []
if (query) {
matchingBooks = booksDB.query(query)
} else {
if (getToken(req)) {
// return a random assortment of 10 books not already in the user's list
matchingBooks = getBooksNotInUsersList(getUser(req).id).slice(0, 10)
} else {
matchingBooks = booksDB.readManyNotInList([]).slice(0, 10)
}
}
return res(ctx.json({books: matchingBooks}))
}),
rest.get(`${apiUrl}/books/:bookId`, async (req, res, ctx) => {
const {bookId} = req.params
const book = booksDB.read(bookId)
if (!book) {
return res(ctx.status(404), ctx.json({message: 'Book not found'}))
}
return res(ctx.json({book}))
}),
rest.get(`${apiUrl}/list-items`, async (req, res, ctx) => {
const user = getUser(req)
const lis = listItemsDB.readByOwner(user.id)
const listItemsAndBooks = lis.map(listItem => ({
...listItem,
book: booksDB.read(listItem.bookId),
}))
return res(ctx.json({listItems: listItemsAndBooks}))
}),
rest.post(`${apiUrl}/list-items`, async (req, res, ctx) => {
const user = getUser(req)
const {bookId} = req.body
const listItem = listItemsDB.create({ownerId: user.id, bookId: bookId})
const book = booksDB.read(bookId)
return res(ctx.json({listItem: {...listItem, book}}))
}),
rest.put(`${apiUrl}/list-items/:listItemId`, async (req, res, ctx) => {
const user = getUser(req)
const {listItemId} = req.params
const updates = req.body
listItemsDB.authorize(user.id, listItemId)
const updatedListItem = listItemsDB.update(listItemId, updates)
const book = booksDB.read(updatedListItem.bookId)
return res(ctx.json({listItem: {...updatedListItem, book}}))
}),
rest.delete(`${apiUrl}/list-items/:listItemId`, async (req, res, ctx) => {
const user = getUser(req)
const {listItemId} = req.params
listItemsDB.authorize(user.id, listItemId)
listItemsDB.remove(listItemId)
return res(ctx.json({success: true}))
}),
rest.post(`${apiUrl}/profile`, async (req, res, ctx) => {
// here's where we'd actually send the report to some real data store.
return res(ctx.json({success: true}))
}),
].map(handler => {
return {
...handler,
async resolver(req, res, ctx) {
try {
const result = await handler.resolver(req, res, ctx)
if (shouldFail(req)) {
throw new Error('Random failure (for testing purposes). Try again.')
}
return result
} catch (error) {
return res(
ctx.status(error.status || 500),
ctx.json({message: error.message || 'Unknown Error'}),
)
} finally {
await sleep()
}
},
}
})
function shouldFail(req) {
if (JSON.stringify(req.body)?.includes('FAIL')) return true
if (req.query.toString()?.includes('FAIL')) return true
if (process.env.NODE_ENV === 'test') return false
const failureRate = Number(
window.localStorage.getItem('__bookshelf_failure_rate__') || 0,
)
return Math.random() < failureRate
}
const getToken = req => req.headers.get('Authorization')?.replace('Bearer ', '')
function getUser(req) {
const token = getToken(req)
if (!token) {
const error = new Error('A token must be provided')
error.status = 401
throw error
}
let userId
try {
userId = atob(token)
} catch (e) {
const error = new Error('Invalid token. Please login again.')
error.status = 401
throw error
}
return usersDB.read(userId)
}
function getBooksNotInUsersList(userId) {
const bookIdsInUsersList = listItemsDB
.readByOwner(userId)
.map(li => li.bookId)
return booksDB.readManyNotInList(bookIdsInUsersList)
}
export {handlers}