-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
85 lines (66 loc) · 2.05 KB
/
Copy pathapp.js
File metadata and controls
85 lines (66 loc) · 2.05 KB
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
85
const express = require('express');
const cors = require('cors');
const passport = require('passport');
const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
const { findUserByIdForJwt } = require('./services/userService');
const app = express();
const authRouter = require('./routes/auth');
const postsRouter = require('./routes/posts');
const userRouter = require('./routes/me');
app.use(express.json({ limit: '50kb' }));
app.use(express.urlencoded({ extended: true, limit: '50kb' }));
const allowedOrigins = ['http://localhost:5173'];
// For production
if (process.env.FRONTEND_URL) {
allowedOrigins.push(process.env.FRONTEND_URL);
}
const corsOptions = {
origin: allowedOrigins,
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization'],
};
app.use(cors(corsOptions));
// Set up how to extract token
const tokenExtractOptions = {
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: process.env.JWT_SECRET,
};
passport.use(
new JwtStrategy(tokenExtractOptions, async (jwt_payload, done) => {
try {
const user = await findUserByIdForJwt(jwt_payload.sub);
if (!user) {
return done(null, false);
}
return done(null, user);
} catch (err) {
return done(err, false);
}
})
);
app.use(passport.initialize());
// Health check
app.get('/health', (req, res) => {
res.status(200).json({
uptime: process.uptime(),
status: 'ok',
});
});
app.use('/auth', authRouter);
app.use('/posts', postsRouter);
app.use('/me', userRouter);
app.use((req, res, next) => {
return res.status(404).json({ error: 'Page Not Found.' });
});
app.use((err, req, res, next) => {
console.error(err);
if (err.type === 'entity.too.large') {
return res.status(413).json({ error: 'Request body is too large.' });
}
return res.status(500).json({ error: 'Something went wrong.' });
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Blog API - listening on port ${PORT}`);
});