-
Notifications
You must be signed in to change notification settings - Fork 33
/
app.ts
80 lines (70 loc) · 2.29 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
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
import 'dotenv/config';
import express from 'express';
import cookieParser from 'cookie-parser';
import next from 'next';
import { createConnection, getConnectionOptions, ConnectionOptions } from 'typeorm';
import path from 'path';
import { WebClient } from '@slack/web-api';
import { PostgresConnectionOptions } from 'typeorm/driver/postgres/PostgresConnectionOptions';
import { slackApp } from './slack';
import { apiApp } from './api';
import logger from './logger';
import { requireAuth } from './api/middleware/requireAuth';
export const app = express();
const nextApp = next({ dev: process.env.NODE_ENV !== 'production' });
const nextHandler = nextApp.getRequestHandler();
let appLoading = true;
// DO NOT PUT THIS LINE IN THIS FILE `express.json()`
app.use(cookieParser(process.env.ADMIN_SECRET)); // lgtm [js/missing-token-validation]
app.get(
'/',
(_req, _res, nextFn) => {
if (appLoading) {
nextFn();
} else {
nextFn('route');
}
},
(_req, res) => {
res.send('👋 Loading');
},
);
app.use('/api', apiApp);
const initDatabase = async (): Promise<void> => {
if (process.env.NODE_ENV !== 'test') {
// Pull connection options from ormconfig.json
const options: ConnectionOptions = await getConnectionOptions();
const url = process.env.DATABASE_URL || (options as PostgresConnectionOptions).url;
await createConnection({
...options,
url,
entities: [path.join(__dirname, 'entities/*')],
migrations: [path.join(__dirname, 'migration/*')],
migrationsRun: true,
} as PostgresConnectionOptions);
}
};
const initSlack = async (): Promise<void> => {
try {
await new WebClient(process.env.SLACK_BOT_TOKEN).auth.test();
app.use(slackApp());
logger.info('Slack setup successfully');
} catch (err) {
logger.error('Slack Bot Token is invalid', err);
if (process.env.NODE_ENV !== 'test') {
process.exit(1);
}
}
};
const initNext = async (): Promise<void> => {
if (process.env.NODE_ENV !== 'test') {
await nextApp.prepare();
app.get(['/'], requireAuth(true), (req, res) => nextHandler(req, res));
app.get('*', (req, res) => nextHandler(req, res));
}
};
export const init = async (): Promise<void> => {
await Promise.all([initDatabase(), initSlack()]);
await initNext();
appLoading = false;
};