contrition/src/index.ts

79 lines
2.4 KiB
TypeScript

import * as cors from "cors";
import * as dotenv from "dotenv";
import * as express from "express";
import { createConnection } from "typeorm";
import { EventEmitter } from "typeorm/platform/PlatformTools";
import Bot from "./bot/Bot";
import { ApiConfig, BotConfig, Config } from "./config/Config";
import { PORT } from "./config/Constants";
import { getApi } from "./controllers/Api";
import { authorize } from "./controllers/Authorize";
import { info } from "./controllers/Info";
import { genOAuth } from "./controllers/OAuth";
import { status } from "./controllers/Status";
import { submit } from "./controllers/Submit";
import { fail } from "./controllers/Util";
import { pruneDB } from "./entity/Cleaner";
dotenv.config();
const config = new Config();
config.api = new ApiConfig(
process.env.CORS_HOST.split(","),
process.env.REDIRECT_URI,
Number(process.env.API_PORT),
process.env.API_CLIENT_SECRET,
process.env.API_CLIENT_ID
);
config.bot = new BotConfig(
process.env.BOT_TOKEN,
process.env.BOT_PREFIX || "con!"
);
// AppealEmitter is used to communicate created appeals from the web form to
// Discord.
const appealEmitter = new EventEmitter();
const app = express();
// JSON parsing middleware
app.use(express.json());
// CORS protection middleware
app.use(cors({ origin: config.api.cors_host }));
// Invalid JSON handler
app.use(
(err: Error, _req: express.Request, res: express.Response, _next: any) => {
if (err instanceof SyntaxError) {
fail(res, 400, "Invalid JSON: " + err.message);
return;
}
console.error("Unhandled Exception", err.message);
fail(res, 500, "Something went wrong!");
}
);
// allow accessing the emitter from the handlers
// this is known as dependency injection!
// We are setting an underlying parameter for the app, which is accessible,
// but not directly passing it around in all of our handlers.
app.set("config", config);
app.set("emitter", appealEmitter);
// endpoints
app.get("/api", getApi);
app.get("/oauth", genOAuth);
app.post("/authorize", authorize);
app.post("/info", info);
app.post("/status", status);
app.post("/submit", submit);
// Conect to the database
createConnection()
.then(async () => {
// Start the API server
app.listen(PORT, () => console.log("Server is listening on port " + PORT));
// Create the Bot with the configuration information and the appeal emitter.
new Bot(config, appealEmitter);
pruneDB(60 * 1000);
})
.catch((err) => console.error(err));