zappyzep/backend/src/api/index.ts

62 lines
1.5 KiB
TypeScript
Raw Normal View History

import { clientError, error, notFound } from "./responses";
2019-05-26 00:13:42 +03:00
import express from "express";
import cors from "cors";
import { initAuth } from "./auth";
import { initGuildsAPI } from "./guilds";
2019-06-23 19:18:41 +03:00
import { initArchives } from "./archives";
2019-08-22 01:22:26 +03:00
import { initDocs } from "./docs";
import { connect } from "../data/db";
import path from "path";
import { TokenError } from "passport-oauth2";
2019-08-04 15:45:35 +03:00
import { PluginError } from "knub";
2019-05-26 00:13:42 +03:00
require("dotenv").config({ path: path.resolve(process.cwd(), "api.env") });
2019-08-04 15:45:35 +03:00
function errorHandler(err) {
2019-08-22 01:22:26 +03:00
console.error(err.stack || err); // tslint:disable-line:no-console
2019-08-04 15:45:35 +03:00
process.exit(1);
}
process.on("unhandledRejection", errorHandler);
2019-08-22 01:22:26 +03:00
console.log("Connecting to database..."); // tslint:disable-line
2019-05-26 00:13:42 +03:00
connect().then(() => {
const app = express();
app.use(
cors({
origin: process.env.DASHBOARD_URL,
}),
);
app.use(express.json());
2019-05-26 00:13:42 +03:00
initAuth(app);
initGuildsAPI(app);
2019-06-23 19:18:41 +03:00
initArchives(app);
2019-08-22 01:22:26 +03:00
initDocs(app);
2019-05-26 00:13:42 +03:00
2019-06-23 19:18:41 +03:00
// Default route
app.get("/", (req, res) => {
2019-07-22 01:13:08 +03:00
res.json({ status: "cookies", with: "milk" });
2019-06-23 19:18:41 +03:00
});
// Error response
app.use((err, req, res, next) => {
if (err instanceof TokenError) {
clientError(res, "Invalid code");
} else {
2019-08-22 01:22:26 +03:00
console.error(err); // tslint:disable-line
error(res, "Server error", err.status || 500);
}
});
2019-06-23 19:18:41 +03:00
// 404 response
app.use((req, res, next) => {
return notFound(res);
2019-05-26 00:13:42 +03:00
});
const port = process.env.PORT || 3000;
2019-08-22 01:22:26 +03:00
// tslint:disable-next-line
2019-05-26 00:13:42 +03:00
app.listen(port, () => console.log(`API server listening on port ${port}`));
});