-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.ts
More file actions
74 lines (64 loc) · 2.19 KB
/
app.ts
File metadata and controls
74 lines (64 loc) · 2.19 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
import express from 'express';
import * as dotenv from 'dotenv';
dotenv.config({ path: __dirname + '/.env' });
import * as http from 'http';
import * as bodyparser from 'body-parser';
import * as winston from 'winston';
import * as expressWinston from 'express-winston';
import serverless from 'serverless-http';
import cors from 'cors';
import { CommonRoutesConfig } from './common/common.routes.config';
import { UserRoutes } from './routes/user.routes.config';
import debug from 'debug';
import mongoose from 'mongoose';
import { verifyToken } from './middleware/verify-token';
const app: express.Application = express();
const server: http.Server = http.createServer(app);
const port = process.env.PORT || 3000;
const routes: Array<CommonRoutesConfig> = [];
const debugLog: debug.IDebugger = debug('app');
// Only connect to MongoDB if MONGO_URL is provided
const mongoUrl = process.env.MONGO_URL || 'mongodb://localhost:27017/tra-api';
mongoose.connect(mongoUrl).catch(console.error);
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
db.once('open', () => {
console.log(`Connected to MongoDB at ${mongoUrl}`);
});
app.use(bodyparser.json());
app.use(cors());
app.use(
expressWinston.logger({
transports: [new winston.transports.Console()],
format: winston.format.combine(
winston.format.colorize(),
winston.format.json()
),
})
);
app.use(
expressWinston.errorLogger({
transports: [new winston.transports.Console()],
format: winston.format.combine(
winston.format.colorize(),
winston.format.json()
),
})
);
app.use(verifyToken);
app.get('/', (req: express.Request, res: express.Response) => {
res.status(200).send(`Server running at http://localhost:${port}`);
});
routes.push(new UserRoutes(app));
if (process.env.SERVERLESS === 'true') {
const lambdaHandler = serverless(app);
module.exports.handler = lambdaHandler;
} else {
server.listen(port, () => {
debugLog(`Server running at http://localhost:${port}`);
console.info(`Server running at http://localhost:${port}`);
routes.forEach((route: CommonRoutesConfig) => {
debugLog(`Routes configured for ${route.getName()}`);
});
});
}