-
Notifications
You must be signed in to change notification settings - Fork 70
/
Copy pathapp.js
81 lines (63 loc) · 1.64 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
const express = require('express')
const app = express()
const passport = require('passport')
const {
users
} = require('./controllers')
/**
* Configure Passport
*/
try { require('./config/passport')(passport) }
catch (error) { console.log(error) }
/**
* Configure Express.js Middleware
*/
// Enable CORS
app.use(function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*')
res.header('Access-Control-Allow-Methods', '*')
res.header('Access-Control-Allow-Headers', '*')
res.header('x-powered-by', 'serverless-express')
next()
})
// Initialize Passport and restore authentication state, if any, from the session
app.use(passport.initialize())
app.use(passport.session())
// Enable JSON use
app.use(express.json())
// Since Express doesn't support error handling of promises out of the box,
// this handler enables that
const asyncHandler = fn => (req, res, next) => {
return Promise
.resolve(fn(req, res, next))
.catch(next);
};
/**
* Routes - Public
*/
app.options(`*`, (req, res) => {
res.status(200).send()
})
app.post(`/users/register`, asyncHandler(users.register))
app.post(`/users/login`, asyncHandler(users.login))
app.get(`/test/`, (req, res) => {
res.status(200).send('Request received')
})
/**
* Routes - Protected
*/
app.post(`/user`, passport.authenticate('jwt', { session: false }), asyncHandler(users.get))
/**
* Routes - Catch-All
*/
app.get(`/*`, (req, res) => {
res.status(404).send('Route not found')
})
/**
* Error Handler
*/
app.use(function (err, req, res, next) {
console.error(err)
res.status(500).json({ error: `Internal Serverless Error - "${err.message}"` })
})
module.exports = app