You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
greenvironment-server/src/app.ts

97 lines
3.1 KiB
TypeScript

5 years ago
import * as compression from "compression";
import connectPgSimple = require("connect-pg-simple");
import * as cookieParser from "cookie-parser";
import * as express from "express";
5 years ago
import * as graphqlHTTP from "express-graphql";
import * as session from "express-session";
import sharedsession = require("express-socket.io-session");
import {buildSchema} from "graphql";
import {importSchema} from "graphql-import";
import * as http from "http";
import * as path from "path";
import * as socketIo from "socket.io";
import dataaccess from "./lib/dataaccess";
import globals from "./lib/globals";
import routes from "./routes";
const logger = globals.logger;
5 years ago
const PgSession = connectPgSimple(session);
class App {
public app: express.Application;
public io: socketIo.Server;
public server: http.Server;
constructor() {
this.app = express();
this.server = new http.Server(this.app);
this.io = socketIo(this.server);
}
/**
* initializes everything that needs to be initialized asynchronous.
*/
public async init() {
await dataaccess.init();
await routes.ioListeners(this.io);
5 years ago
const appSession = session({
cookie: {
maxAge: Number(globals.config.session.cookieMaxAge) || 604800000,
5 years ago
secure: "auto",
},
resave: false,
saveUninitialized: false,
5 years ago
secret: globals.config.session.secret,
store: new PgSession({
pool: dataaccess.pool,
tableName: "user_sessions",
}),
});
this.io.use(sharedsession(appSession, {autoSave: true}));
this.app.set("views", path.join(__dirname, "views"));
this.app.set("view engine", "pug");
5 years ago
this.app.set("trust proxy", 1);
this.app.use(compression());
this.app.use(express.json());
this.app.use(express.urlencoded({extended: false}));
this.app.use(express.static(path.join(__dirname, "public")));
5 years ago
this.app.use(cookieParser());
this.app.use(appSession);
this.app.use((req, res, next) => {
logger.verbose(`${req.method} ${req.url}`);
next();
});
this.app.use(routes.router);
this.app.use("/graphql", graphqlHTTP((request, response) => {
5 years ago
return {
// @ts-ignore all
context: {session: request.session},
graphiql: true,
rootValue: routes.resolvers(request, response),
schema: buildSchema(importSchema(path.join(__dirname, "./public/graphql/schema.graphql"))),
5 years ago
};
}));
}
/**
* Starts the web server.
*/
public start() {
if (globals.config.server.port) {
logger.info(`Starting server...`);
this.app.listen(globals.config.server.port);
logger.info(`Server running on port ${globals.config.server.port}`);
} else {
logger.error("No port specified in the config." +
"Please configure a port in the config.yaml.");
}
}
}
export default App;