瀏覽代碼

refactor: moved io module handlers to be in namespaces and added util module

Kristian Vos 4 年之前
父節點
當前提交
fc0bd5c0a7

+ 1 - 0
backend/index.js

@@ -160,6 +160,7 @@ module.exports = moduleManager;
 
 moduleManager.addModule("logger");
 moduleManager.addModule("io");
+moduleManager.addModule("util");
 moduleManager.addModule("mongo");
 
 moduleManager.initialize();

+ 17 - 197
backend/logic/io/index.js

@@ -11,221 +11,41 @@ const express = require("express");
 const http = require("http");
 const socketio = require('socket.io');
 
-let temporaryAutosuggestCache = {};
-let temporaryAutosuggestMap = {};
-
 module.exports = class extends coreClass {
 	constructor(name, moduleManager) {
 		super(name, moduleManager);
 
-		this.dependsOn = ["mongo"];
+		this.dependsOn = ["mongo", "util"];
 	}
 
 	initialize() {
-		return new Promise(resolve => {
+		return new Promise(async resolve => {
 			this.setStage(1);
-			
+
 			const app = express();
 			const server = http.createServer(app);
 			const io = socketio(server);
 
 			this.mongo = this.moduleManager.modules["mongo"];
+			this.util = this.moduleManager.modules["util"];
 
-			this.mongo.models.accountSchema.find({}, null, { sort: "-version", limit: 1 }, (err, res) => {
-				if (!err) {
-					res[0].fields.forEach(field => {
-						field.fieldTypes.forEach(fieldType => {
-							if (fieldType.type === "text" && fieldType.autosuggestGroup) {
-								temporaryAutosuggestMap[`${field.fieldId}.${fieldType.fieldTypeId}`] = fieldType.autosuggestGroup;
-								temporaryAutosuggestCache[fieldType.autosuggestGroup] = [];
-							}
-						});
-					});
-
-					this.mongo.models.account.find({}, (err, accounts) => {
-						if (!err) {
-							accounts.forEach(account => {
-								Object.keys(temporaryAutosuggestMap).forEach(key => {
-									let autosuggestGroup = temporaryAutosuggestMap[key];
-									let fieldId = key.split(".")[0];
-									let fieldTypeId = key.split(".")[1];
-									account.fields[fieldId].forEach(field => {
-										if (temporaryAutosuggestCache[autosuggestGroup].indexOf(field[fieldTypeId]) === -1)
-											temporaryAutosuggestCache[autosuggestGroup].push(field[fieldTypeId]);
-									});
-								});
-							});
-
-							console.log(temporaryAutosuggestCache);
-							console.log(temporaryAutosuggestMap);
-						}
-					});
-				}
-			});
-
-			
-
-			this.handlers = {
-				"getAutosuggest": cb => {
-					cb({
-						autosuggest: temporaryAutosuggestCache
-					});
-				},
-
-				"getAccounts": cb => {
-					this.mongo.models.account.find({}, (err, accounts) => {
-						if (err)
-							return cb({
-								status: "failure",
-								err: err
-							});
-						else
-							return cb({
-								status: "success",
-								accounts
-							});
-					});
-				},
-
-				"getAccount": (cb, accountId) => {
-					this.mongo.models.account.findById(accountId, (err, account) => {
-						if (err || !account)
-							return cb({
-								status: "failure",
-								err: err
-							});
-						else
-							return cb({
-								status: "success",
-								account
-							});
-					});
-				},
-
-				"addAccount": (cb, account) => {
-					this.mongo.models.account.create(account, (err) => {
-						if (err)
-							return cb({
-								status: "failure",
-								err: err
-							});
-						else {
-							Object.keys(temporaryAutosuggestMap).forEach(key => {
-								let autosuggestGroup = temporaryAutosuggestMap[key];
-								let fieldId = key.split(".")[0];
-								let fieldTypeId = key.split(".")[1];
-								account.fields[fieldId].forEach(field => {
-									if (temporaryAutosuggestCache[autosuggestGroup].indexOf(field[fieldTypeId]) === -1)
-										temporaryAutosuggestCache[autosuggestGroup].push(field[fieldTypeId]);
-								});
-							});
-							console.log("Added account!");
-							return cb({
-								status: "success"
-							});
-						}
-					});
-				},
-
-				"editAccount": (cb, accountId, account) => {
-					this.mongo.models.account.updateOne({ _id: accountId }, account, (err) => {
-						if (err)
-							return cb({
-								status: "failure",
-								err: err
-							});
-						else {
-							Object.keys(temporaryAutosuggestMap).forEach(key => {
-								let autosuggestGroup = temporaryAutosuggestMap[key];
-								let fieldId = key.split(".")[0];
-								let fieldTypeId = key.split(".")[1];
-								account.fields[fieldId].forEach(field => {
-									if (temporaryAutosuggestCache[autosuggestGroup].indexOf(field[fieldTypeId]) === -1)
-										temporaryAutosuggestCache[autosuggestGroup].push(field[fieldTypeId]);
-								});
-							});
-							console.log("Editted account!");
-							return cb({
-								status: "success"
-							});
-						}
-					});
-				},
-
-				"getAccountSchema": cb => {
-					this.mongo.models.accountSchema.find({}, null, { sort: "-version", limit: 1 }, (err, res) => {
-						if (err || !res || res.length !== 1)
-							return cb({
-								status: "failure",
-								message: "Something went wrong."
-							});
-						else
-							return cb({
-								status: "success",
-								schema: res[0]
-							});
-					});
-				},
-
-				"getAccountSchemas": cb => {
-					this.mongo.models.accountSchema.find({}, null, { sort: "-version" }, (err, res) => {
-						if (err || !res)
-							return cb({
-								status: "failure",
-								message: "Something went wrong."
-							});
-						else
-							return cb({
-								status: "success",
-								schemas: res
-							});
-					});
-				},
-
-				"getAccountSchemaById": (cb, schemaId) => {
-					this.mongo.models.accountSchema.findById(schemaId, (err, res) => {
-						if (err || !res)
-							return cb({
-								status: "failure",
-								message: "Something went wrong."
-							});
-						else
-							return cb({
-								status: "success",
-								schema: res
-							});
-					});
-				},
-
-				"importAccountSchema": (cb, name) => {
-					let schema = require(`../schemas/${name}`);
-					this.mongo.models.accountSchema.create(schema, (err) => {
-						if (err)
-							return cb({
-								status: "failure",
-								err: err
-							});
-						else
-							return cb({
-								status: "success"
-							});
-					});
-				}
-			}
+			this.namespaces = require("./namespaces");
 
 			io.on('connection', (socket) => {
 				console.log('a user connected');
 
-				Object.keys(this.handlers).forEach(handlerName => {
-					socket.on(handlerName, (...args) => {
-						let cb = args[args.length - 1];
-						if (typeof cb !== "function")
-							cb = () => {
-								this.logger.info("IO_MODULE", `There was no callback provided for ${name}.`);
-							}
-						else args.pop();
-
-						this.handlers[handlerName].apply(null, [cb].concat(args));
+				Object.keys(this.namespaces).forEach(namespaceName => {
+					Object.keys(this.namespaces[namespaceName]).forEach(handlerName => {
+						socket.on(`${namespaceName}.${handlerName}`, (...args) => {
+							let cb = args[args.length - 1];
+							if (typeof cb !== "function")
+								cb = () => {
+									this.logger.info("IO_MODULE", `There was no callback provided for ${name}.`);
+								}
+							else args.pop();
+
+							this.namespaces[namespaceName][handlerName].apply(null, [cb].concat(args));
+						});
 					});
 				});
 			});

+ 78 - 0
backend/logic/io/namespaces/account.js

@@ -0,0 +1,78 @@
+const moduleManager = require("../../../index");
+
+const mongoModule = moduleManager.modules["mongo"];
+const utilModule = moduleManager.modules["util"];
+
+module.exports = {
+	"getAll": async cb => {
+		mongoModule.models.then(models => {
+			models.account.find({}, (err, accounts) => {
+				if (err)
+					return cb({
+						status: "failure",
+						err: err
+					});
+				else
+					return cb({
+						status: "success",
+						accounts
+					});
+			});
+		});
+	},
+
+	"getById": (cb, accountId) => {
+		mongoModule.models.then(models => {
+			models.account.findById(accountId, (err, account) => {
+				if (err || !account)
+					return cb({
+						status: "failure",
+						err: err
+					});
+				else
+					return cb({
+						status: "success",
+						account
+					});
+			});
+		});
+	},
+
+	"add": (cb, account) => {
+		mongoModule.models.then(models => {
+			models.account.create(account, (err) => {
+				if (err)
+					return cb({
+						status: "failure",
+						err: err
+					});
+				else {
+					utilModule.addAutosuggestAccount(account);
+					console.log("Added account!");
+					return cb({
+						status: "success"
+					});
+				}
+			});
+		});
+	},
+
+	"editById": (cb, accountId, account) => {
+		mongoModule.models.then(models => {
+			models.account.updateOne({ _id: accountId }, account, (err) => {
+				if (err)
+					return cb({
+						status: "failure",
+						err: err
+					});
+				else {
+					utilModule.addAutosuggestAccount(account);
+					console.log("Editted account!");
+					return cb({
+						status: "success"
+					});
+				}
+			});
+		});
+	}
+}

+ 74 - 0
backend/logic/io/namespaces/accountSchema.js

@@ -0,0 +1,74 @@
+const moduleManager = require("../../../index");
+
+const mongoModule = moduleManager.modules["mongo"];
+
+module.exports = {
+	"getLatest": cb => {
+		mongoModule.models.then(models => {
+			models.accountSchema.find({}, null, { sort: "-version", limit: 1 }, (err, res) => {
+				if (err || !res || res.length !== 1)
+					return cb({
+						status: "failure",
+						message: "Something went wrong."
+					});
+				else
+					return cb({
+						status: "success",
+						schema: res[0]
+					});
+			});
+		});
+	},
+
+	"getAll": cb => {
+		mongoModule.models.then(models => {
+			models.accountSchema.find({}, null, { sort: "-version" }, (err, res) => {
+				if (err || !res)
+					return cb({
+						status: "failure",
+						message: "Something went wrong."
+					});
+				else
+					return cb({
+						status: "success",
+						schemas: res
+					});
+			});
+		});
+	},
+
+	"getById": (cb, schemaId) => {
+		mongoModule.models.then(models => {
+			models.accountSchema.findById(schemaId, (err, res) => {
+				if (err || !res)
+					return cb({
+						status: "failure",
+						message: "Something went wrong."
+					});
+				else
+					return cb({
+						status: "success",
+						schema: res
+					});
+			});
+		});
+	},
+
+	"import": (cb, name) => {
+		mongoModule.models.then(models => {
+			mongoModule.schemas.then(models => {
+				models.accountSchema.create(schemas[name], (err) => {
+					if (err)
+						return cb({
+							status: "failure",
+							err: err
+						});
+					else
+						return cb({
+							status: "success"
+						});
+				});
+			});
+		});
+	}
+}

+ 5 - 0
backend/logic/io/namespaces/index.js

@@ -0,0 +1,5 @@
+module.exports = {
+	account: require("./account.js"),
+	accountSchema: require("./accountSchema.js"),
+	util: require("./util.js")
+}

+ 11 - 0
backend/logic/io/namespaces/util.js

@@ -0,0 +1,11 @@
+const moduleManager = require("../../../index");
+
+const utilModule = moduleManager.modules["util"];
+
+module.exports = {
+	"getAutosuggest": async cb => {
+		cb({
+			autosuggest: await utilModule.autosuggestCache
+		});
+	}
+}

+ 20 - 6
backend/logic/mongo/index.js

@@ -14,8 +14,8 @@ module.exports = class extends coreClass {
 		return new Promise((resolve, reject) => {
 			this.setStage(1);
 
-			this.schemas = {};
-			this.models = {};
+			this._schemas = {};
+			this._models = {};
 
 			const mongoUrl = config.get("mongo").url;
 
@@ -26,14 +26,14 @@ module.exports = class extends coreClass {
 				reconnectTries: 10
 			})
 				.then(() => {
-					this.schemas = {
+					this._schemas = {
 						accountSchema: new mongoose.Schema(require(`./schemas/accountSchema`)),
 						account: new mongoose.Schema(require(`./schemas/account`))
 					};
 		
-					this.models = {
-						accountSchema: mongoose.model('accountSchema', this.schemas.accountSchema),
-						account: mongoose.model('account', this.schemas.account)
+					this._models = {
+						accountSchema: mongoose.model('accountSchema', this._schemas.accountSchema),
+						account: mongoose.model('account', this._schemas.account)
 					};
 
 					mongoose.connection.on('error', err => {
@@ -207,4 +207,18 @@ module.exports = class extends coreClass {
 				});
 		})
 	}
+
+	get schemas() {
+		return new Promise(async resolve => {
+			try { await this._validateHook(); } catch { return; }
+			resolve(this._schemas);
+		});
+	}
+
+	get models() {
+		return new Promise(async resolve => {
+			try { await this._validateHook(); } catch { return; }
+			resolve(this._models);
+		});
+	}
 }

+ 95 - 0
backend/logic/util.js

@@ -0,0 +1,95 @@
+'use strict';
+
+const async = require("async");
+
+const coreClass = require("../core");
+
+const config = require('config');
+
+module.exports = class extends coreClass {
+	constructor(name, moduleManager) {
+		super(name, moduleManager);
+
+		this.dependsOn = ["mongo"];
+	}
+
+	initialize() {
+		return new Promise((resolve, reject) => {
+			this.setStage(1);
+
+			this.mongo = this.moduleManager.modules["mongo"];
+
+			this._autosuggestCache = {};
+			this._autosuggestMap = {};
+
+			async.waterfall([
+				(next) => {
+					this.mongo.models.then(models => {
+						models.accountSchema.find({}, null, { sort: "-version", limit: 1 }, next);
+					});
+				},
+
+				(schemas, next) => {
+					schemas[0].fields.forEach(field => {
+						field.fieldTypes.forEach(fieldType => {
+							if (fieldType.type === "text" && fieldType.autosuggestGroup) {
+								this._autosuggestMap[`${field.fieldId}.${fieldType.fieldTypeId}`] = fieldType.autosuggestGroup;
+								this._autosuggestCache[fieldType.autosuggestGroup] = [];
+							}
+						});
+					});
+
+					this.mongo.models.then(models => {
+						models.account.find({}, next);
+					});
+				},
+
+				(accounts, next) => {
+					accounts.forEach(account => {
+						Object.keys(this._autosuggestMap).forEach(key => {
+							let autosuggestGroup = this._autosuggestMap[key];
+							let fieldId = key.split(".")[0];
+							let fieldTypeId = key.split(".")[1];
+							account.fields[fieldId].forEach(field => {
+								if (this._autosuggestCache[autosuggestGroup].indexOf(field[fieldTypeId]) === -1)
+									this._autosuggestCache[autosuggestGroup].push(field[fieldTypeId]);
+							});
+						});
+					});
+
+					next();
+				}
+			], (err) => {
+				if (err) reject(new Error(err));
+				else resolve();
+			});
+		})
+	}
+
+	get autosuggestCache() {
+		return new Promise(async resolve => {
+			try { await this._validateHook(); } catch { return; }
+			resolve(this._autosuggestCache);
+		});
+	}
+
+	get autosuggestMap() {
+		return new Promise(async resolve => {
+			try { await this._validateHook(); } catch { return; }
+			resolve(this._autosuggestMap);
+		});
+	}
+
+	async addAutosuggestAccount(account) {
+		try { await this._validateHook(); } catch { return; }
+		Object.keys(this._autosuggestMap).forEach(key => {
+			let autosuggestGroup = this._autosuggestMap[key];
+			let fieldId = key.split(".")[0];
+			let fieldTypeId = key.split(".")[1];
+			account.fields[fieldId].forEach(field => {
+				if (this._autosuggestCache[autosuggestGroup].indexOf(field[fieldTypeId]) === -1)
+					this._autosuggestCache[autosuggestGroup].push(field[fieldTypeId]);
+			});
+		});
+	}
+}

+ 2 - 2
frontend/vue/components/AccountForm.vue

@@ -50,7 +50,7 @@ export default {
 		io.getSocket(socket => {
 			this.socket = socket;
 
-			socket.emit("getAccountSchema", res => {
+			socket.emit("accountSchema.getLatest", res => {
 				this.fields = res.schema.fields;
 				if (!this.initialAccount) {
 					this.account.fields = {};
@@ -74,7 +74,7 @@ export default {
 				}
 			});
 
-			socket.emit("getAutosuggest", res => {
+			socket.emit("util.getAutosuggest", res => {
 				this.autosuggest = res.autosuggest;
 			});
 		});

+ 2 - 1
frontend/vue/pages/Accounts.vue

@@ -29,7 +29,8 @@ export default {
 		io.getSocket(socket => {
 			this.socket = socket;
 
-			socket.emit("getAccounts", res => {
+			socket.emit("account.getAll", res => {
+				console.log(res);
 				this.accounts = res.accounts;
 			});
 		});

+ 1 - 1
frontend/vue/pages/AddAccount.vue

@@ -16,7 +16,7 @@ export default {
 	},
 	methods: {
 		onSubmit(account) {
-			this.socket.emit("addAccount", account, (res) => {
+			this.socket.emit("account.add", account, (res) => {
 				console.log(res);
 				if (res.status === "success") {
 					this.$router.push("/")

+ 2 - 2
frontend/vue/pages/EditAccount.vue

@@ -17,7 +17,7 @@ export default {
 	},
 	methods: {
 		onSubmit(account) {
-			this.socket.emit("editAccount", account._id, account, (res) => {
+			this.socket.emit("account.editById", account._id, account, (res) => {
 				console.log(res);
 				if (res.status === "success") {
 					this.$router.push("/")
@@ -30,7 +30,7 @@ export default {
 		io.getSocket(socket => {
 			this.socket = socket;
 
-			this.socket.emit("getAccount", this.accountId, res => {
+			this.socket.emit("account.getById", this.accountId, res => {
 				console.log(res);
 				if (res.status === "success") {
 					this.account = res.account;

+ 2 - 2
frontend/vue/pages/Schemas.vue

@@ -20,7 +20,7 @@ export default {
 	},
 	methods: {
 		importAccountSchema() {
-			this.socket.emit("importAccountSchema", this.importAccountSchemaName, (res) => {
+			this.socket.emit("accountSchema.import", this.importAccountSchemaName, (res) => {
 				console.log(res);
 				alert(res.status);
 			});
@@ -30,7 +30,7 @@ export default {
 		io.getSocket(socket => {
 			this.socket = socket;
 
-			this.socket.emit("getAccountSchemas", res => {
+			this.socket.emit("accountSchema.getAll", res => {
 				this.schemas = res.schemas;
 			});
 		});

+ 1 - 1
frontend/vue/pages/ViewSchema.vue

@@ -51,7 +51,7 @@ export default {
 		io.getSocket(socket => {
 			this.socket = socket;
 
-			this.socket.emit("getAccountSchemaById", this.schemaId, res => {
+			this.socket.emit("accountSchema.getLatest", this.schemaId, res => {
 				if (res.status === "success") {
 					this.schema = res.schema;
 				}