-
Notifications
You must be signed in to change notification settings - Fork 0
/
example.mjs
84 lines (68 loc) · 1.91 KB
/
example.mjs
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
import RestLib from './src/rest.js'
import { parseBodyMiddleware } from './src/utils.js'
const onlyAuthorizedMiddleware = (ctx, next) => {
if (ctx.user) {
next()
} else {
ctx.response.send({ error: 'Unauthorized' }, 401)
}
}
const ROOT_DIR = process.cwd()
const app = new RestLib()
app.use(parseBodyMiddleware)
app.use((ctx, next) => {
const { queryParams } = ctx.request
ctx.user = ctx.request.queryParams ? { name: queryParams.name } : null
next()
})
app.use((ctx, next) => {
const { method, url } = ctx.request
console.log(`${method}: ${url}`)
next()
})
// All POST requests should be authorized
app.post('/*', onlyAuthorizedMiddleware)
app.all('/list/*', (ctx, next) => {
console.log(`Operation with the list was requested by ${ctx.user ? ctx.user.name : 'anonymous'}`)
next()
})
app.get('/', (ctx) => {
ctx.response.send({ message: 'Hello World' })
})
app.get('/file/:file', (ctx) => {
const { file } = ctx.request.params
ctx.response.sendFile(`${ROOT_DIR}/${file}`)
})
const list = []
// This two listeners is equal to app.get('/list', listener1, listener2)
app.get('/list', (ctx, next) => {
ctx.list = list.map(item => item ** 2)
next()
})
app.get('/list', (ctx) => {
ctx.response.send({ data: ctx.list })
})
app.get('/list/:id', (ctx) => {
ctx.response.send({ data: list[ctx.request.params.id] })
})
/**
* Example of request:
*
* URL: http://localhost:3000/list?name="John"
* BODY: { "data": 10 }
*/
app.post('/list', (ctx, next) => {
list.push(ctx.request.body.data)
ctx.response.send({ data: list })
next()
}, (ctx) => {
console.log(`The element ${ctx.request.body.data} was added to the list`)
})
app.put('/list', onlyAuthorizedMiddleware, (ctx, next) => {
list.push(ctx.request.body.data)
ctx.response.send({ data: list })
next()
})
app.listen(3000, () => {
console.log('Server started on port 3000')
})