@acadix/setup
Version:
Acadix Learning Management System backend application project setup
194 lines • 7.99 kB
JavaScript
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ExpressRouter = exports.AppConfig = void 0;
const dotenv = __importStar(require("dotenv"));
dotenv.config();
require("express-async-errors");
const express_1 = __importStar(require("express"));
Object.defineProperty(exports, "ExpressRouter", { enumerable: true, get: function () { return express_1.Router; } });
const cors_1 = __importDefault(require("cors"));
const helmet_1 = __importDefault(require("helmet"));
const express_rate_limit_1 = __importDefault(require("express-rate-limit"));
const compression_1 = __importDefault(require("compression"));
const swagger_ui_express_1 = __importDefault(require("swagger-ui-express"));
const middlewares_1 = require("../middlewares");
const utils_1 = require("../utils");
const logger_1 = require("../logger");
/**
* Application Config Files
*/
class App {
constructor(env) {
this.env = env;
this.env = env;
this.app = (0, express_1.default)();
this.config();
this.defaultRoute();
this.db = new utils_1.DBConnection(this.env);
this.redis = new utils_1.RedisConnection(this.env);
this.kafka = new utils_1.KafkaConnection(this.env);
this.mail = new utils_1.MailConnection(this.env);
this.logger = (0, logger_1.Logger)(this.env);
this.consul = new utils_1.ConsulConnection(this.env.CONSUL);
}
config() {
this.app.use(express_1.default.json());
this.app.use(express_1.default.urlencoded({
extended: false,
}));
this.app.disable("x-powered-by");
this.app.use((0, helmet_1.default)());
this.app.use(helmet_1.default.noSniff());
this.app.use(helmet_1.default.contentSecurityPolicy({
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "'unsafe-inline'"],
styleSrc: ["'self'", "'unsafe-inline'"],
},
}));
this.app.set("trust proxy", this.env.APP_ENV === "production");
this.app.use((0, cors_1.default)({}));
this.app.use((0, express_rate_limit_1.default)({
windowMs: 1 * 60 * 1000,
max: 5,
skipSuccessfulRequests: true,
handler: function (req, res, next, options) {
utils_1.ResponseHandler.error(res, {
message: options.message,
statusCode: utils_1.StatusCode.TOO_MANY_REQUEST,
});
},
}));
this.app.use((0, compression_1.default)());
const apiLogMiddleware = new logger_1.ReqLog(this.env.SERVICE).getMiddleware();
this.app.use(apiLogMiddleware);
}
defaultRoute() {
//Default Routes
this.app.get(`/api/v1/${this.env.SERVICE}/`, (req, res) => {
utils_1.ResponseHandler.success(res, {
message: `Acadix ${this.env.SERVICE} test route`,
data: {
start: "Hello World",
},
});
});
this.app.get("/health", (req, res) => {
utils_1.ResponseHandler.success(res, {
message: "Service Discovery test",
data: `${this.env.SERVICE} still running successfully`
});
});
}
getApp() {
return this.app;
}
defaultRouting(routeHandler, unit) {
const baseRoute = unit ? `/api/v1/${unit}` : `/api/v1`;
this.app.use(baseRoute, routeHandler);
}
createDocumentation(doc) {
this.app.get(`/api/v1/${this.env.SERVICE}/doc`, (req, res) => {
utils_1.ResponseHandler.success(res, {
message: `${this.env.SERVICE} documentation(JSON FORMAT)`,
data: doc,
});
});
this.app.use(`/api/v1/${this.env.SERVICE}/docs`, swagger_ui_express_1.default.serve, swagger_ui_express_1.default.setup(doc));
}
appMiddlewares() {
//Favicon Middleware
this.app.use(middlewares_1.FaviconMiddleware);
//Not Found Middleware
this.app.use(middlewares_1.NotFoundMiddleware);
//Error Handler Middleware
this.app.use(middlewares_1.ErrorHandlerMiddleware);
}
Kafka() {
if (this.env.KAFKA) {
return this.kafka;
}
else {
return "Kafka configuration variables missing";
}
}
WhatsappAPI() {
const whatsapp = new utils_1.WhatsappCloudAPI(this.env);
return whatsapp;
}
Redis() {
if (this.env.REDIS) {
return this.redis;
}
else {
return "Redis configuration variables missing";
}
}
DB() {
return this.db.db;
}
startServer(app_port) {
return __awaiter(this, void 0, void 0, function* () {
this.appMiddlewares();
this.consul.registerConsulService(app_port);
if (this.env.REDIS) {
yield this.redis.createRedisConnection();
}
if (this.env.KAFKA) {
this.kafka.connectKafka();
}
yield this.db.createDatabaseConnection();
this.app
.listen(app_port, () => {
this.logger.info(`Server listening on port ${app_port} and running in ${this.env.APP_ENV} mode...`);
})
.on("error", (error) => {
this.logger.error(`Error starting server: ${error.message}`);
process.exit(1);
});
const signal = "SIGINT" || "SIGTERM" || "SIGQUIT";
process.on(signal, () => __awaiter(this, void 0, void 0, function* () {
yield this.db.closeDatabaseConnection();
yield this.redis.closeRedisConnection();
process.exit(0);
}));
});
}
}
exports.AppConfig = App;
//# sourceMappingURL=app.config.js.map