forked from CodeGenieApp/serverless-express
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
83 lines (65 loc) · 2.03 KB
/
app.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
'use strict'
const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const compression = require('compression')
const awsServerlessExpressMiddleware = require('aws-serverless-express/middleware')
const app = express()
app.set('view engine', 'pug')
app.use(compression())
app.use(cors())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
app.use(awsServerlessExpressMiddleware.eventContext())
app.get('/', (req, res) => {
res.render('index', {
apiUrl: req.apiGateway ? `https://${req.apiGateway.event.headers.Host}/${req.apiGateway.event.requestContext.stage}` : 'http://localhost:3000'
})
})
app.get('/sam', (req, res) => {
res.sendFile(`${__dirname}/sam-logo.png`)
})
app.get('/users', (req, res) => {
res.json(users)
})
app.get('/users/:userId', (req, res) => {
const user = getUser(req.params.userId)
if (!user) return res.status(404).json({})
return res.json(user)
})
app.post('/users', (req, res) => {
const user = {
id: ++userIdCounter,
name: req.body.name
}
users.push(user)
res.status(201).json(user)
})
app.put('/users/:userId', (req, res) => {
const user = getUser(req.params.userId)
if (!user) return res.status(404).json({})
user.name = req.body.name
res.json(user)
})
app.delete('/users/:userId', (req, res) => {
const userIndex = getUserIndex(req.params.userId)
if(userIndex === -1) return res.status(404).json({})
users.splice(userIndex, 1)
res.json(users)
})
const getUser = (userId) => users.find(u => u.id === parseInt(userId))
const getUserIndex = (userId) => users.findIndex(u => u.id === parseInt(userId))
// Ephemeral in-memory data store
const users = [{
id: 1,
name: 'Joe'
}, {
id: 2,
name: 'Jane'
}]
let userIdCounter = users.length
// The aws-serverless-express library creates a server and listens on a Unix
// Domain Socket for you, so you can remove the usual call to app.listen.
// app.listen(3000)
// Export your express server so you can import it in the lambda function.
module.exports = app