From f68e7df2234029ab228a613bb848ed8a0e19dee5 Mon Sep 17 00:00:00 2001 From: Ben <36240171+benkyd@users.noreply.github.com> Date: Tue, 8 Feb 2022 18:01:10 +0000 Subject: [PATCH] bro Former-commit-id: ccc7bc8c7bf361055c0a021fdad567a1e62f3ed3 --- src/config.js | 10 +++---- src/database/database.js | 26 ++++++++++++++----- .../entity-relationships.js | 17 +++++++----- ...nships.js => relationships_constraints.js} | 8 ++++-- src/database/psql-entity-framework/types.js | 4 +++ src/index.js | 13 ++++++---- src/logger.js | 18 ++++++------- src/models/lego-brick.js | 24 +++++++++++++++++ src/models/model-manager.js | 19 ++++++++++++++ src/routes/server.js | 10 +++---- 10 files changed, 109 insertions(+), 40 deletions(-) rename src/database/psql-entity-framework/{relationships.js => relationships_constraints.js} (62%) create mode 100644 src/models/lego-brick.js create mode 100644 src/models/model-manager.js diff --git a/src/config.js b/src/config.js index 8f4df98..cb12b5b 100644 --- a/src/config.js +++ b/src/config.js @@ -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 } diff --git a/src/database/database.js b/src/database/database.js index fe439c7..f11c83f 100644 --- a/src/database/database.js +++ b/src/database/database.js @@ -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') +} diff --git a/src/database/psql-entity-framework/entity-relationships.js b/src/database/psql-entity-framework/entity-relationships.js index 591e735..d064825 100644 --- a/src/database/psql-entity-framework/entity-relationships.js +++ b/src/database/psql-entity-framework/entity-relationships.js @@ -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...'); } } diff --git a/src/database/psql-entity-framework/relationships.js b/src/database/psql-entity-framework/relationships_constraints.js similarity index 62% rename from src/database/psql-entity-framework/relationships.js rename to src/database/psql-entity-framework/relationships_constraints.js index 31e031d..335952e 100644 --- a/src/database/psql-entity-framework/relationships.js +++ b/src/database/psql-entity-framework/relationships_constraints.js @@ -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 }; } } diff --git a/src/database/psql-entity-framework/types.js b/src/database/psql-entity-framework/types.js index 9bd3ce5..2cf084b 100644 --- a/src/database/psql-entity-framework/types.js +++ b/src/database/psql-entity-framework/types.js @@ -11,6 +11,10 @@ class DataTypes { return 'BIGINT'; } + static get DECIMAL() { + return 'DECIMAL'; + } + static get TEXT() { return 'TEXT'; } diff --git a/src/index.js b/src/index.js index fdd8c47..f4b3d55 100644 --- a/src/index.js +++ b/src/index.js @@ -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(); diff --git a/src/logger.js b/src/logger.js index 6a4a28d..fa40b72 100644 --- a/src/logger.js +++ b/src/logger.js @@ -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() + '] [' diff --git a/src/models/lego-brick.js b/src/models/lego-brick.js new file mode 100644 index 0000000..e1fdd41 --- /dev/null +++ b/src/models/lego-brick.js @@ -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 +} diff --git a/src/models/model-manager.js b/src/models/model-manager.js new file mode 100644 index 0000000..e3fb9a7 --- /dev/null +++ b/src/models/model-manager.js @@ -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 +} diff --git a/src/routes/server.js b/src/routes/server.js index a312799..c12f15e 100644 --- a/src/routes/server.js +++ b/src/routes/server.js @@ -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 };