kodex-music-catalog/server.js
2023-10-02 11:55:35 +03:00

94 lines
2.1 KiB
JavaScript

"use strict";
const express = require("express");
const bodyHand = require("body");
const config = require("./config-handler");
const http = require("http");
const { Database } = require("./database");
const app = express();
global.database = new Database(
config().database.address,
config().database.port,
config().database.username,
config().database.password,
config().database.database,
);
http.ServerResponse.prototype.errorModeOn = function () {
this.isError = true;
};
http.ServerResponse.prototype.bindNext = function (next) {
this.next = next;
};
http.ServerResponse.prototype.sendModed = function (sendData) {
// Модифицируем res.send
if (sendData !== undefined && config().logger_mode) {
this.responseData = sendData;
require("./logger")(this.req, this, this.next);
}
this.send(sendData);
};
app.use((req, res, next) => {
res.bindNext(next);
next();
});
app.use((req, res, next) => {
// Для добавления оригинального тела запроса
const body = bodyHand(
req,
res,
{
limit: 9999999999,
cache: false,
encoding: "base64",
},
(err, body) => {
if (!err) {
req.byteBody = Buffer.from(body, "base64");
// Запись в req.json при json
if (!!req.headers && req.headers["content-type"]?.includes("json")) {
try {
req.json = JSON.parse(req.byteBody.toString("utf8"));
} catch (_e) {}
}
}
next();
},
);
});
app.use("/", async (rq, rs, next) => next(), require("./page-view"));
app.use("/api", async (rq, rs, next) => next(), require("./api"));
// Подключение через HTTPS
let server;
if (!config().ssl.enabled) {
server = app;
} else {
const https = require("https");
server = https.createServer(
{
cert: fs.readFileSync(config().ssl["public"], "utf-8"),
key: fs.readFileSync(config().ssl["private"], "utf-8"),
},
app,
);
}
server.listen(config().port, config().address, async (err) => {
if (err) {
throw err;
} else {
console.log(
`Kodex Muzic catalog runned at ${config().address}:${config().port}`,
);
}
});