-
Notifications
You must be signed in to change notification settings - Fork 59
/
api-helper.js
69 lines (63 loc) · 1.83 KB
/
api-helper.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
import { createServer } from '../lib/server'
import { memoize } from 'lodash'
import axios from 'axios'
/**
* API helper to make it easier to test endpoints.
*/
export async function apiHelper() {
const server = await startServer()
const baseURL = `http://127.0.0.1:${server.address().port}`
const client = axios.create({
baseURL
})
return {
catch: catchAndLog, // Useful for logging failing requests
client,
// Add your app-specific methods here.
findTodos: params =>
client.get(`/todos`, { params }).then(assertStatus(200)),
getTodo: id => client.get(`/todos/${id}`).then(assertStatus(200)),
createTodo: data => client.post('/todos', data).then(assertStatus(201)),
updateTodo: (id, data) =>
client.patch(`/todos/${id}`, data).then(assertStatus(200)),
removeTodo: id => client.delete(`/todos/${id}`).then(assertStatus(204))
}
}
/**
* Creates a status asserter that asserts the given status on the response,
* then returns the response data.
*
* @param {number} status
*/
export function assertStatus(status) {
return async function statusAsserter(resp) {
if (resp.status !== status) {
throw new Error(
`Expected ${status} but got ${resp.status}: ${resp.request.method} ${
resp.request.path
}`
)
}
return resp.data
}
}
function catchAndLog(err) {
if (err.response) {
console.error(
`Error ${err.response.status} in request ${err.response.request.method} ${
err.response.request.path
}`,
err.response.data
)
}
throw err
}
const startServer = memoize(async () => {
return (await createServer()).listen()
})
afterAll(async () => {
// Server is memoized so it won't start a new one.
// We need to close it.
const server = await startServer()
return new Promise(resolve => server.close(resolve))
})