MusicTopus/src/app.js

130 lines
3.3 KiB
JavaScript

import path from "path";
import express from "express";
import cookieParser from "cookie-parser";
import passport from "passport";
import mongoose from "mongoose";
import flash from "connect-flash";
import session from "express-session";
import MongoStore from "connect-mongo";
import config, { env, mongoDbUri, secret } from "./config";
import { isXhr } from "./helpers";
import indexRouter from "./routes";
import importAlbumRouterApiV1 from "./routes/api/v1/albums";
import importSearchRouterApiV1 from "./routes/api/v1/search";
// Mongoose schema init
require("./models/users");
require("./models/albums");
require("./libs/passport")(passport);
mongoose
.connect(mongoDbUri, { useNewUrlParser: true, useUnifiedTopology: true })
.catch(() => {
process.exit();
});
const sess = {
cookie: {
maxAge: 86400000,
},
secret,
saveUninitialized: false,
resave: false,
store: MongoStore.create({
mongoUrl: mongoDbUri,
mongoOptions: { useNewUrlParser: true, useUnifiedTopology: true },
}),
};
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(flash());
app.use(session(sess));
if (["production"].indexOf(env) !== -1) {
app.enable("trust proxy", 1);
sess.cookie.secure = true;
/* eslint-disable func-names */
app.use((req, res, next) => {
if (req.secure) {
next();
} else {
res.redirect(`https://${req.headers.host}${req.url}`);
}
});
}
app.use(passport.initialize());
app.use(passport.session());
app.set("views", path.join(__dirname, "../views"));
app.set("view engine", "ejs");
app.use(express.static(path.join(__dirname, "../public")));
app.use(
"/libs/vue",
express.static(path.join(__dirname, "../node_modules/vue/dist"))
);
app.use(
"/libs/axios",
express.static(path.join(__dirname, "../node_modules/axios/dist"))
);
app.use("/", indexRouter);
app.use("/api/v1/albums", importAlbumRouterApiV1);
app.use("/api/v1/search", importSearchRouterApiV1);
// Handle 404
app.use((req, res) => {
if (isXhr(req)) {
res.status(404).send({ message: "404: Not found" });
} else {
res.status(404).render("index", {
page: { title: `404: Cette page n'existe pas.` },
errorCode: 404,
viewname: "error",
user: req.user || null,
config,
session: req.session || null,
flashInfo: null,
query: null,
params: null,
error: null,
});
}
});
// Handle 500
app.use((error, req, res, next) => {
if (isXhr(req)) {
const { message, errorCode, date } = error;
res.status(error.errorCode || 500).send({ message, errorCode, date });
} else {
res.status(error.errorCode || 500);
res.render("index", {
page: { title: "500: Oups… le serveur a crashé !", error },
errorCode: error.errorCode || 500,
viewname: "error",
user: req.user || null,
config,
session: req.session || null,
flashInfo: null,
query: null,
params: null,
error: null,
});
next();
}
});
export default app;