-
Notifications
You must be signed in to change notification settings - Fork 342
/
using-middleware.js
58 lines (54 loc) · 1.43 KB
/
using-middleware.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
const middy = require('middy')
const { jsonBodyParser, validator, httpErrorHandler, httpHeaderNormalizer } = require('middy/middlewares')
/* Normal lambda code */
const businessLogic = (event, context, callback) => {
// event.body has already been turned into an object by `jsonBodyParser` middleware
const { name } = event.body
return callback(null, {
statusCode: 200,
body: JSON.stringify({
result: 'success',
message: `Hi ${name} ⊂◉‿◉つ`
})
})
}
/* Input & Output Schema */
const schema = {
input: {
type: 'object',
properties: {
body: {
type: 'object',
required: ['name'],
properties: {
name: { type: 'string' }
}
}
},
required: ['body']
},
output: {
type: 'object',
properties: {
body: {
type: 'string',
required: ['result', 'message'],
properties: {
result: { type: 'string' },
message: { type: 'string' }
}
}
},
required: ['body']
}
}
/* Export inputSchema & outputSchema for automatic documentation */
exports.schema = schema
exports.handler = middy(businessLogic)
.use(httpHeaderNormalizer())
// parses the request body when it's a JSON and converts it to an object
.use(jsonBodyParser())
// validates the input
.use(validator({ inputSchema: schema.input }))
// handles common http errors and returns proper responses
.use(httpErrorHandler())