feat(settings): added in settings
This commit is contained in:
315
app/main.ts
315
app/main.ts
@@ -1,200 +1,201 @@
|
||||
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
|
||||
|
||||
import { toNodeHandler } from "better-auth/node";
|
||||
import cors from "cors";
|
||||
import express from "express";
|
||||
import morgan from "morgan";
|
||||
import { createServer } from "http";
|
||||
import { setupRoutes } from "./src/internal/routerHandler/routeHandler.js";
|
||||
import { printers } from "./src/internal/ocp/printers/printers.js";
|
||||
import morgan from "morgan";
|
||||
import os from "os";
|
||||
import { dirname, join } from "path";
|
||||
import { fileURLToPath } from "url";
|
||||
import { schedulerManager } from "./src/internal/logistics/controller/schedulerManager.js";
|
||||
import { printers } from "./src/internal/ocp/printers/printers.js";
|
||||
import { setupRoutes } from "./src/internal/routerHandler/routeHandler.js";
|
||||
import { baseSettings } from "./src/internal/system/controller/settings/baseSettings.js";
|
||||
import { auth } from "./src/pkg/auth/auth.js";
|
||||
import { db } from "./src/pkg/db/db.js";
|
||||
import { settings } from "./src/pkg/db/schema/settings.js";
|
||||
import { validateEnv } from "./src/pkg/utils/envValidator.js";
|
||||
import { createLogger } from "./src/pkg/logger/logger.js";
|
||||
import { returnFunc } from "./src/pkg/utils/return.js";
|
||||
import { initializeProdPool } from "./src/pkg/prodSql/prodSqlConnect.js";
|
||||
import { tryCatch } from "./src/pkg/utils/tryCatch.js";
|
||||
import os from "os";
|
||||
import cors from "cors";
|
||||
import { sendNotify } from "./src/pkg/utils/notify.js";
|
||||
import { toNodeHandler } from "better-auth/node";
|
||||
import { auth } from "./src/pkg/auth/auth.js";
|
||||
import { v1Listener } from "./src/pkg/logger/v1Listener.js";
|
||||
import { apiHitMiddleware } from "./src/pkg/middleware/apiHits.js";
|
||||
import { initializeProdPool } from "./src/pkg/prodSql/prodSqlConnect.js";
|
||||
import { validateEnv } from "./src/pkg/utils/envValidator.js";
|
||||
import { sendNotify } from "./src/pkg/utils/notify.js";
|
||||
import { returnFunc } from "./src/pkg/utils/return.js";
|
||||
import { tryCatch } from "./src/pkg/utils/tryCatch.js";
|
||||
import { setupIoServer } from "./src/ws/server.js";
|
||||
import { schedulerManager } from "./src/internal/logistics/controller/schedulerManager.js";
|
||||
|
||||
const main = async () => {
|
||||
const env = validateEnv(process.env);
|
||||
const PORT = Number(env.VITE_PORT) || 4200;
|
||||
const env = validateEnv(process.env);
|
||||
const PORT = Number(env.VITE_PORT) || 4200;
|
||||
|
||||
//create the logger
|
||||
const log = createLogger({ module: "system", subModule: "main start" });
|
||||
//create the logger
|
||||
const log = createLogger({ module: "system", subModule: "main start" });
|
||||
|
||||
// base path
|
||||
let basePath: string = "";
|
||||
// base path
|
||||
let basePath: string = "";
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = dirname(__filename);
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = dirname(__filename);
|
||||
|
||||
// Db connection stuff
|
||||
const res = await tryCatch(db.select().from(settings));
|
||||
// Db connection stuff
|
||||
const res = await tryCatch(db.select().from(settings));
|
||||
|
||||
if (res.error) {
|
||||
return returnFunc({
|
||||
success: false,
|
||||
module: "system",
|
||||
level: "fatal",
|
||||
message: `Database lookup failed`,
|
||||
notify: false,
|
||||
data: [],
|
||||
});
|
||||
}
|
||||
if (res.error) {
|
||||
return returnFunc({
|
||||
success: false,
|
||||
module: "system",
|
||||
level: "fatal",
|
||||
message: `Database lookup failed`,
|
||||
notify: false,
|
||||
data: [],
|
||||
});
|
||||
}
|
||||
|
||||
if (res.data.length === 0) {
|
||||
//return
|
||||
// returnFunc({
|
||||
// success: false,
|
||||
// module: "system",
|
||||
// level: "fatal",
|
||||
// message: `This seems to be the first time you have started the app please validate the settings have been intiated`,
|
||||
// notify: false,
|
||||
// data: [],
|
||||
// });
|
||||
}
|
||||
if (res.data.length === 0) {
|
||||
//return
|
||||
// returnFunc({
|
||||
// success: false,
|
||||
// module: "system",
|
||||
// level: "fatal",
|
||||
// message: `This seems to be the first time you have started the app please validate the settings have been intiated`,
|
||||
// notify: false,
|
||||
// data: [],
|
||||
// });
|
||||
}
|
||||
|
||||
// connect to the prod sql
|
||||
await initializeProdPool();
|
||||
// connect to the prod sql
|
||||
await initializeProdPool();
|
||||
|
||||
// express app
|
||||
const app = express();
|
||||
// express app
|
||||
const app = express();
|
||||
|
||||
// global env that run only in dev
|
||||
if (process.env.NODE_ENV?.trim() !== "production") {
|
||||
app.use(morgan("tiny"));
|
||||
basePath = "/lst";
|
||||
// global env that run only in dev
|
||||
if (process.env.NODE_ENV?.trim() !== "production") {
|
||||
app.use(morgan("tiny"));
|
||||
basePath = "/lst";
|
||||
|
||||
app.use(
|
||||
basePath + "/test",
|
||||
express.static(join(__dirname, "../controller"))
|
||||
);
|
||||
}
|
||||
app.use(
|
||||
basePath + "/test",
|
||||
express.static(join(__dirname, "../controller")),
|
||||
);
|
||||
}
|
||||
|
||||
// global middleware
|
||||
app.set("trust proxy", true);
|
||||
app.use(apiHitMiddleware);
|
||||
app.all(basePath + "/api/auth/*splat", toNodeHandler(auth)); // sign-in sign-out
|
||||
app.use(express.json());
|
||||
// global middleware
|
||||
app.set("trust proxy", true);
|
||||
app.use(apiHitMiddleware);
|
||||
app.all(basePath + "/api/auth/*splat", toNodeHandler(auth)); // sign-in sign-out
|
||||
app.use(express.json());
|
||||
|
||||
const allowedOrigins = [
|
||||
/^https?:\/\/localhost:(5173|5500|4200|3000|4000)$/, // all the allowed backend ports
|
||||
/^https?:\/\/.*\.alpla\.net$/,
|
||||
env.BETTER_AUTH_URL, // prod
|
||||
];
|
||||
const allowedOrigins = [
|
||||
/^https?:\/\/localhost:(5173|5500|4200|3000|4000)$/, // all the allowed backend ports
|
||||
/^https?:\/\/.*\.alpla\.net$/,
|
||||
env.BETTER_AUTH_URL, // prod
|
||||
];
|
||||
|
||||
app.use(
|
||||
cors({
|
||||
origin: (origin, callback) => {
|
||||
//console.log("CORS request from origin:", origin);
|
||||
app.use(
|
||||
cors({
|
||||
origin: (origin, callback) => {
|
||||
//console.log("CORS request from origin:", origin);
|
||||
|
||||
if (!origin) return callback(null, true); // allow same-site or direct calls
|
||||
if (!origin) return callback(null, true); // allow same-site or direct calls
|
||||
|
||||
try {
|
||||
const hostname = new URL(origin).hostname; // strips protocol/port
|
||||
//console.log("Parsed hostname:", hostname);
|
||||
try {
|
||||
const hostname = new URL(origin).hostname; // strips protocol/port
|
||||
//console.log("Parsed hostname:", hostname);
|
||||
|
||||
if (allowedOrigins.includes(origin)) {
|
||||
return callback(null, true);
|
||||
}
|
||||
if (allowedOrigins.includes(origin)) {
|
||||
return callback(null, true);
|
||||
}
|
||||
|
||||
// Now this works for *.alpla.net
|
||||
if (
|
||||
hostname.endsWith(".alpla.net") ||
|
||||
hostname === "alpla.net"
|
||||
) {
|
||||
return callback(null, true);
|
||||
}
|
||||
} catch (err) {
|
||||
//console.error("Invalid Origin header:", origin);
|
||||
}
|
||||
// Now this works for *.alpla.net
|
||||
if (hostname.endsWith(".alpla.net") || hostname === "alpla.net") {
|
||||
return callback(null, true);
|
||||
}
|
||||
} catch (err) {
|
||||
//console.error("Invalid Origin header:", origin);
|
||||
}
|
||||
|
||||
return callback(new Error("Not allowed by CORS: " + origin));
|
||||
},
|
||||
methods: ["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"],
|
||||
credentials: true,
|
||||
})
|
||||
);
|
||||
return callback(new Error("Not allowed by CORS: " + origin));
|
||||
},
|
||||
methods: ["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"],
|
||||
credentials: true,
|
||||
}),
|
||||
);
|
||||
|
||||
// docs and api stuff
|
||||
app.use(
|
||||
basePath + "/d",
|
||||
express.static(join(__dirname, "../lstDocs/build"))
|
||||
);
|
||||
app.use(
|
||||
basePath + "/app",
|
||||
express.static(join(__dirname, "../frontend/dist"))
|
||||
);
|
||||
// docs and api stuff
|
||||
app.use(basePath + "/d", express.static(join(__dirname, "../lstDocs/build")));
|
||||
app.use(
|
||||
basePath + "/app",
|
||||
express.static(join(__dirname, "../frontend/dist")),
|
||||
);
|
||||
|
||||
// server setup
|
||||
const server = createServer(app);
|
||||
// server setup
|
||||
const server = createServer(app);
|
||||
|
||||
// register app
|
||||
setupRoutes(app, basePath);
|
||||
// register app
|
||||
setupRoutes(app, basePath);
|
||||
|
||||
// ws stuff
|
||||
setupIoServer(server, basePath);
|
||||
// ws stuff
|
||||
setupIoServer(server, basePath);
|
||||
|
||||
// sub systems
|
||||
printers();
|
||||
schedulerManager();
|
||||
// start all systems after we are intiallally up and running
|
||||
setTimeout(() => {
|
||||
baseSettings();
|
||||
printers();
|
||||
schedulerManager();
|
||||
|
||||
// start the server up
|
||||
server.listen(PORT, "0.0.0.0", () =>
|
||||
log.info(
|
||||
{ stack: { name: "test" } },
|
||||
`Server running in ${
|
||||
process.env.NODE_ENV ? process.env.NODE_ENV : "dev"
|
||||
}, on http://0.0.0.0:${PORT}${basePath}`
|
||||
)
|
||||
);
|
||||
// start up the v1listener
|
||||
v1Listener();
|
||||
}, 5 * 1000);
|
||||
|
||||
process.on("uncaughtException", async (err) => {
|
||||
//console.log("Uncaught Exception:", err);
|
||||
// await closePool();
|
||||
// const emailData = {
|
||||
// email: "blake.matthes@alpla.com", // should be moved to the db so it can be reused.
|
||||
// subject: `${os.hostname()} has just encountered a crash.`,
|
||||
// template: "serverCrash",
|
||||
// context: {
|
||||
// error: err,
|
||||
// plant: `${os.hostname()}`,
|
||||
// },
|
||||
// };
|
||||
// start the server up
|
||||
server.listen(PORT, "0.0.0.0", () =>
|
||||
log.info(
|
||||
{ stack: { name: "test" } },
|
||||
`Server running in ${
|
||||
process.env.NODE_ENV ? process.env.NODE_ENV : "dev"
|
||||
}, on http://0.0.0.0:${PORT}${basePath}`,
|
||||
),
|
||||
);
|
||||
|
||||
if (!process.env.WEBHOOK_URL) {
|
||||
// await sendEmail(emailData);
|
||||
} else {
|
||||
log.fatal({ stack: err.stack }, err.message);
|
||||
await sendNotify({
|
||||
module: "system",
|
||||
subModule: "fatalCrash",
|
||||
hostname: os.hostname(),
|
||||
message: err.message,
|
||||
stack: err?.stack,
|
||||
});
|
||||
}
|
||||
process.on("uncaughtException", async (err) => {
|
||||
//console.log("Uncaught Exception:", err);
|
||||
// await closePool();
|
||||
// const emailData = {
|
||||
// email: "blake.matthes@alpla.com", // should be moved to the db so it can be reused.
|
||||
// subject: `${os.hostname()} has just encountered a crash.`,
|
||||
// template: "serverCrash",
|
||||
// context: {
|
||||
// error: err,
|
||||
// plant: `${os.hostname()}`,
|
||||
// },
|
||||
// };
|
||||
|
||||
//process.exit(1);
|
||||
});
|
||||
if (!process.env.WEBHOOK_URL) {
|
||||
// await sendEmail(emailData);
|
||||
} else {
|
||||
log.fatal({ stack: err.stack }, err.message);
|
||||
await sendNotify({
|
||||
module: "system",
|
||||
subModule: "fatalCrash",
|
||||
hostname: os.hostname(),
|
||||
message: err.message,
|
||||
stack: err?.stack,
|
||||
});
|
||||
}
|
||||
|
||||
// setInterval(() => {
|
||||
// const used = process.memoryUsage();
|
||||
// console.log(
|
||||
// `Heap: ${(used.heapUsed / 1024 / 1024).toFixed(2)} MB / RSS: ${(
|
||||
// used.rss /
|
||||
// 1024 /
|
||||
// 1024
|
||||
// ).toFixed(2)} MB`
|
||||
// );
|
||||
// }, 10000);
|
||||
//process.exit(1);
|
||||
});
|
||||
|
||||
// setInterval(() => {
|
||||
// const used = process.memoryUsage();
|
||||
// console.log(
|
||||
// `Heap: ${(used.heapUsed / 1024 / 1024).toFixed(2)} MB / RSS: ${(
|
||||
// used.rss / 1024 / 1024
|
||||
// ).toFixed(2)} MB`,
|
||||
// );
|
||||
// }, 10000);
|
||||
};
|
||||
|
||||
main();
|
||||
|
||||
Reference in New Issue
Block a user