-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.ts
49 lines (43 loc) · 1.46 KB
/
app.ts
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
import express, { Request, Response, NextFunction } from 'express';
import morgan from 'morgan';
import createError, { HttpError } from 'http-errors';
import productRoutes from './routes/products';
import orderRoutes from './routes/orders';
import userRoutes from './routes/users';
import authenticate from './middleware/authenticate';
const app = express();
// Middleware
app.use(morgan('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use((req: Request, res: Response, next: NextFunction) => {
res.header('Access-Control-Allow-Origin', '*');
res.header(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept, Authorization'
);
if (req.method === 'OPTIONS') {
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE');
return res.status(200).json({});
}
next();
});
// Routes
app.use('/products', productRoutes);
app.use('/orders', authenticate, orderRoutes);
app.use('/users', userRoutes);
app.use('/status', (req: Request, res: Response) => {
return res.status(200).send('Server up and running');
});
// Non existing routes
app.use((req: Request, res: Response, next: Function) => {
const error = new createError.NotFound();
return next(error);
});
// Error handling
app.use((error: HttpError, req: Request, res: Response, next: NextFunction) => {
res
.status(error.status || 500)
.json({ message: error.message || 'Server error' });
});
export default app;