Former-commit-id: ccc7bc8c7bf361055c0a021fdad567a1e62f3ed3
This commit is contained in:
Ben
2022-02-08 18:01:10 +00:00
parent da98e813db
commit f68e7df223
10 changed files with 109 additions and 40 deletions

View File

@@ -3,10 +3,10 @@ const Logger = require('./logger.js');
const dotenv = require('dotenv');
function load() {
Logger.info('Loading Config...');
Logger.Info('Loading Config...');
const res = dotenv.config();
Logger.debug(`CONFIG: ${JSON.stringify(res.parsed)}`);
Logger.debug(`CONFIG: running in ${res.parsed.NODE_ENV} mode`);
Logger.Debug(`CONFIG: ${JSON.stringify(res.parsed)}`);
Logger.Debug(`CONFIG: running in ${res.parsed.NODE_ENV} mode`);
// if NODE_ENV is dev, every config item that is dev is made into the actual one so that the
// individual modules do not need to care about hte mode of operation
@@ -15,7 +15,7 @@ function load() {
if (key.endsWith('_DEV')) {
const newKey = key.substring(0, key.length - 4);
process.env[newKey] = res.parsed[key];
Logger.debug(`CONFIG KEY: '${newKey}' DEVELOPMENT VALUE: '${process.env[newKey]}'`);
Logger.Debug(`CONFIG KEY: '${newKey}' DEVELOPMENT VALUE: '${process.env[newKey]}'`);
}
});
}
@@ -23,5 +23,5 @@ function load() {
}
module.exports = {
load
Load: load
}

View File

@@ -1,4 +1,5 @@
const Logger = require('../logger.js');
const EntityFramework = require('./psql-entity-framework/entity-relationships.js');
const { Client } = require('pg');
@@ -8,7 +9,7 @@ class Database {
}
async connect(options) {
Logger.info('Database Connecting...');
Logger.Info('Database Connecting...');
// review options
if (!options) {
@@ -24,24 +25,35 @@ class Database {
this.options = options;
this.connection = await this.connectToDatabase();
Logger.info('Database Connected');
Logger.Info('Database Connected');
}
async connectToDatabase() {
return new Promise((resolve, reject) => {
const con = new Promise((resolve, reject) => {
const psqlClient = new Client(this.options);
psqlClient.connect();
psqlClient.query('SELECT NOW()', (err, res) => {
if (err) reject(err);
this.connection = psqlClient;
Logger.database(`PSQL Time: ${res.rows[0].now}`);
Logger.database(`Connected to ${this.options.host}`);
Logger.Database(`PSQL Time: ${res.rows[0].now}`);
Logger.Database(`Connected to ${this.options.host}`);
resolve(psqlClient);
});
});
await con;
this.ORM = new EntityFramework(this.connection);
return this.connection;
}
get getORM() {
return this.ORM;
}
}
module.exports = Database;
module.exports = {
IDatabase: Database,
DataTypes: require('./psql-entity-framework/types.js'),
DataConstraints: require('./psql-entity-framework/relationships_constraints.js')
}

View File

@@ -1,12 +1,15 @@
const Logger = require('../../logger.js');
const DataTypes = require('./types.js');
class PSQLObjectRelation {
constructor(psqlConnection) {
this.connection = psqlConnection;
Logger.Database('ORM Loading...');
this.connection = psqlConnection;;
this.models = {}
}
async AddModel(name, model) {
Logger.database(`ORM Adding ${name}`);
async addModel(name, model, constraints) {
Logger.Database(`ORM Adding ${name}`);
let sql = `CREATE TABLE IF NOT EXISTS ${name} (`;
let keys = Object.keys(model);
for (let i = 0; i < keys.length; i++) {
@@ -16,12 +19,12 @@ class PSQLObjectRelation {
if (i < keys.length - 1) sql += ', ';
}
sql += ');';
Logger.database(sql);
await this.connection.query(sql);
Logger.Database(sql);
// await this.connection.query(sql);
}
async SyncModels() {
Logger.database('ORM Syncing...');
async syncModels() {
Logger.Database('ORM Syncing...');
}
}

View File

@@ -1,4 +1,8 @@
class RelationshipTypes {
static PRIMARY_KEY() {
return "PRIMARY KEY";
}
static get UNIQUE() {
return 'UNIQUE';
}
@@ -11,8 +15,8 @@ class RelationshipTypes {
return 'REFERENCES';
}
static FOREIGN_KEY(localKey, foreignKey) {
return `FOREIGN KEY (${localKey}) REFERENCES ${foreignKey}`;
static FOREIGN_KEY(references) {
return { references };
}
}

View File

@@ -11,6 +11,10 @@ class DataTypes {
return 'BIGINT';
}
static get DECIMAL() {
return 'DECIMAL';
}
static get TEXT() {
return 'TEXT';
}

View File

@@ -3,16 +3,19 @@ const Config = require('./config.js');
const Server = require('./routes/server.js');
const Databse = require('./database/database.js');
const ModelManager = require('./models/model-manager.js');
async function main() {
Logger.info('Pre-Init Loading...');
Logger.init();
Config.load();
Logger.Info('Pre-Init Loading...');
Logger.Init();
Config.Load();
const Database = new Databse();
const Database = new Databse.IDatabase();
await Database.connect();
Server.listen(process.env.PORT);
ModelManager.Init(Database);
Server.Listen(process.env.PORT);
}
main();

View File

@@ -10,7 +10,7 @@ let dateFormat = 'DD-MM-YY HH:mm:ss'
// must be ran after the config is initalised
// TODO: network logs
module.exports.init = async function(path) {
module.exports.Init = async function(path) {
if (path) logPath = path;
// ALWAYS logs to console, others are aditionals
@@ -41,7 +41,7 @@ module.exports.DEBUG_LOGS = 1;
module.exports.INFO_LOGS = 2;
module.exports.WARN_LOGS = 3;
module.exports.middleware = function(origin, message) {
module.exports.Middleware = function(origin, message) {
let d = moment().format(dateFormat);
fs.appendFileSync(logPath, `[${d.toLocaleString()}] [MIDDLEWARE: ${origin}] ${message} \n`);
if (LogLevel > 0) return;
@@ -49,7 +49,7 @@ module.exports.middleware = function(origin, message) {
+ clc.yellow(`MIDDLEWARE: ${origin}`) + '] ' + message);
}
module.exports.database = function(message) {
module.exports.Database = function(message) {
let d = moment().format(dateFormat);
fs.appendFileSync(logPath, `[${d.toLocaleString()}] [POSTGRES: SQL] ${message} \n`);
if (LogLevel > 0) return;
@@ -57,7 +57,7 @@ module.exports.database = function(message) {
+ clc.magentaBright(`POSTGRES: SQL`) + '] ' + message);
}
module.exports.debug = function(message) {
module.exports.Debug = function(message) {
let d = moment().format(dateFormat);
fs.appendFileSync(logPath, `[${d.toLocaleString()}] [DEBUG] ${message} \n`);
if (LogLevel > 1) return;
@@ -65,14 +65,14 @@ module.exports.debug = function(message) {
+ clc.cyan('DEBUG') + '] ' + message);
}
module.exports.ready = function() {
module.exports.Ready = function() {
let d = moment().format(dateFormat);
fs.appendFileSync(logPath, `[${d.toLocaleString()}] [READY] \n`);
console.log('[' + d.toLocaleString() + '] ['
+ clc.rainbow('READY') + ']');
}
module.exports.info = function(message) {
module.exports.Info = function(message) {
let d = moment().format(dateFormat);
fs.appendFileSync(logPath, `[${d.toLocaleString()}] [INFO] ${message} \n`);
if (LogLevel > 2) return;
@@ -80,7 +80,7 @@ module.exports.info = function(message) {
+ clc.green('INFO') + '] ' + message);
}
module.exports.warn = function(message) {
module.exports.Warn = function(message) {
let d = moment().format(dateFormat);
fs.appendFileSync(logPath, `[${d.toLocaleString()}] [WARN] ${message} \n`);
if (LogLevel > 3) return;
@@ -88,14 +88,14 @@ module.exports.warn = function(message) {
+ clc.yellow('WARN') + '] ' + message);
}
module.exports.error = function(message) {
module.exports.Error = function(message) {
let d = moment().format(dateFormat);
fs.appendFileSync(logPath, `[${d.toLocaleString()}] [ERROR] ${message} \n`);
console.error('[' + d.toLocaleString() + '] ['
+ clc.red('ERROR') + '] ' + message);
}
module.exports.panic = function(message) {
module.exports.Panic = function(message) {
let d = moment().format(dateFormat);
fs.appendFileSync(logPath, `[${d.toLocaleString()}] [PANIC] ${message} \n`);
console.error('[' + d.toLocaleString() + '] ['

24
src/models/lego-brick.js Normal file
View File

@@ -0,0 +1,24 @@
const Models = require('./model-manager.js');
const { DataTypes, DataConstraints } = require('../database/database.js');
const { ORM } = Models.Database;
async function init() {
ORM.addModel('lego_brick', {
id: {
type: DataTypes.VARCHAR(50),
constraints: [ DataConstraints.PRIMARY_KEY, DataConstraints.NOT_NULL ]
},
catagory: {
type: DataTypes.INTEGER,
constraints: [ DataConstraints.FOREIGN_KEY(ORM.model('catagory').property('id')) ]
},
date_released: DataTypes.DATE,
dimenions_x: DataTypes.DECIMAL,
dimenions_y: DataTypes.DECIMAL,
dimenions_z: DataTypes.DECIMAL,
});
}
module.exports = {
Init: init
}

View File

@@ -0,0 +1,19 @@
const fs = require('fs');
function init(databaseInstance) {
module.exports.Database = databaseInstance;
module.exports.Models = {};
let files = fs.readdirSync(__dirname);
files.forEach(file => {
if (file !== 'model-manager.js') {
const model = require(`./${file}`);
module.exports.Models[file.split('.')[0]] = model;
model.Init();
}
});
}
module.exports = {
Init: init
}

View File

@@ -5,21 +5,21 @@ const app = express();
function logRequest(req, res, next)
{
Logger.middleware('REQUEST', `${req.originalUrl} [${req.method}: ${req.headers['x-forwarded-for'] || req.socket.remoteAddress }]`);
Logger.Middleware('REQUEST', `${req.originalUrl} [${req.method}: ${req.headers['x-forwarded-for'] || req.socket.remoteAddress }]`);
next();
}
function listen(port) {
app.listen(port);
Logger.info(`Listening on ${port}...`);
Logger.Info(`Listening on ${port}...`);
Logger.info(`Setting up basic middleware...`);
Logger.Info(`Setting up basic middleware...`);
app.use(logRequest);
app.use(express.static('client/public/'));
}
module.exports = {
app,
listen
App: app,
Listen: listen
};