-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
182 lines (156 loc) · 4.61 KB
/
index.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
import dotenv from "dotenv";
import express from "express";
import dayjs from "dayjs";
import utc from "dayjs/plugin/utc";
import timezone from "dayjs/plugin/timezone";
import swaggerJsdoc from "swagger-jsdoc";
import swaggerUi from "swagger-ui-express";
import bodyParser = require("body-parser");
import cron = require("node-cron");
import "reflect-metadata";
import {
ConnectionOptions,
createConnection,
getConnection,
getRepository,
LessThan
} from "typeorm";
import { Order } from "./entity/order";
import { Production } from "./entity/production";
import { Show } from "./entity/show";
import { Discount } from "./entity/discount";
// libraries
import { seedDB } from "./dev";
import { Payment } from "./entity/payment";
import { Ticket } from "./entity/ticket";
import { TicketType } from "./entity/ticket_type";
import { VenueSeat } from "./entity/venue_seat";
import Logger from "./logging";
import getMainRouter from "./main";
import getAdminRouter from "./admin";
// initialise config
dotenv.config();
dayjs.extend(utc);
dayjs.extend(timezone);
// TODO: change this if we ever change
dayjs.tz.setDefault("Australia/Sydney")
const app = express();
const API_PORT = process.env.SERVER_PORT;
const API_HOST = "http://localhost";
app.use(genericLoggingMiddleware);
const swaggerjsdocOptions: any = {
apis: ["./dist/**/*.js"],
swaggerDefinition: {
info: {
description: "API for the Revue Booking System site with autogenerated swagger docs",
title: "Revue Booking System API",
version: "1.0.0",
},
},
};
const specs = swaggerJsdoc(swaggerjsdocOptions);
const activeEntities = [
Production,
Show,
Order,
Payment,
TicketType,
Ticket,
VenueSeat,
Discount
];
const options: ConnectionOptions = {
database: process.env.MYSQL_DATABASE,
entities: activeEntities,
host: "localhost",
logging: false,
migrations: [
// "src/migration/**/*.ts"
],
password: process.env.MYSQL_PASSWD,
port: 3306,
subscribers: [
// "src/subscriber/**/*.ts"
],
synchronize: true,
type: "mysql",
username: process.env.MYSQL_USER,
};
function genericLoggingMiddleware(req: express.Request, res: express.Response, next: express.NextFunction) {
function afterResponse() {
res.removeListener("finish", afterResponse);
res.removeListener("close", afterResponse);
Logger.Info(`${req.method} ${res.statusCode} - ${req.path}`);
}
res.on("finish", afterResponse);
res.on("close", afterResponse);
next();
}
// setup
async function bootstrap() {
Logger.Info("Creating database connection...");
await createConnection(options);
if (process.env.NODE_ENV === "development") {
Logger.Info("Development environment: to clear the tables, go to /reset");
}
if (process.env.NODE_ENV === "test") {
Logger.Info("Test environment: will purge database");
resetDB();
}
}
async function resetDB() {
Logger.Info("Purging the database tables...");
// Can't use .clear() as TRUNCATE doesn't work with foreign key constraints.
/*await Promise.all(
activeEntities.map(async (entity) => await getRepository(entity).delete({}))
);*/
for (const entity of activeEntities) {
await getRepository(entity).delete({});
}
Logger.Info("Seeding database...");
await seedDB();
}
Logger.Init();
app.use(bodyParser.json());
if (process.env.NODE_ENV === "development" || process.env.NODE_ENV === "test") {
Logger.Info(`API documentation available at ${API_HOST}:${API_PORT}/docs`);
app.use("/docs", swaggerUi.serve, swaggerUi.setup(specs));
app.get("/reset", async function (_, res) {
try {
await resetDB();
res.json({success: true});
} catch (err) {
Logger.Error(err.stack);
res.status(500).json({error: "Internal server error"});
}
});
let now = dayjs().tz();
console.log(now.format());
}
app.listen(API_PORT, async () => {
await bootstrap();
Logger.Info(`Server started at ${API_HOST}:${API_PORT}`);
});
if (process.env.NODE_ENV !== "test") {
// Remove unpaid orders if they've been left there.
/*
cron.schedule('* * * * *', async () => {
try {
const repo = getRepository(Order);
Logger.Info("Purging unpaid orders...");
const toDelete = await repo.find({
// FIXME: apparently this doesn't work on sqlite but does on MySQL???
// https://github.com/typeorm/typeorm/issues/2286
updatedAt: LessThan(new Date(Date.now() - 20 * 60 * 1000)),
paid: false
});
await repo.remove(toDelete);
Logger.Info(`purge: ${toDelete.length} unpaid orders removed.`);
} catch (e) {
console.error(e);
}
});
*/
}
app.use('/admin', getAdminRouter());
app.use('/', getMainRouter());