jcc-express-mvc 1.1.8 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jcc-express-mvc",
3
- "version": "1.1.8",
3
+ "version": "1.2.0",
4
4
  "description": "express mvc structure",
5
5
  "main": "index.js",
6
6
  "scripts": {
@@ -39,7 +39,8 @@ class Router {
39
39
  * @returns {Router} - Returns the router instance.
40
40
  */
41
41
  get(path, callback) {
42
- this.util.routeHelper("get", path, callback);
42
+ this.util.routeHttpMethod("get", path, callback);
43
+ this.middlewares = null;
43
44
  return this;
44
45
  }
45
46
 
@@ -50,7 +51,8 @@ class Router {
50
51
  * @returns {Router} - Returns the router instance.
51
52
  */
52
53
  post(path, callback) {
53
- this.util.routeHelper("post", path, callback);
54
+ this.util.routeHttpMethod("post", path, callback);
55
+ this.middlewares = null;
54
56
  return this;
55
57
  }
56
58
 
@@ -61,7 +63,8 @@ class Router {
61
63
  * @returns {Router} - Returns the router instance.
62
64
  */
63
65
  patch(path, callback) {
64
- this.util.routeHelper("patch", path, callback);
66
+ this.util.routeHttpMethod("patch", path, callback);
67
+ this.middlewares = null;
65
68
  return this;
66
69
  }
67
70
 
@@ -72,7 +75,8 @@ class Router {
72
75
  * @returns {Router} - Returns the router instance.
73
76
  */
74
77
  put(path, callback) {
75
- this.util.routeHelper("put", path, callback);
78
+ this.util.routeHttpMethod("put", path, callback);
79
+ this.middlewares = null;
76
80
  return this;
77
81
  }
78
82
 
@@ -83,14 +87,27 @@ class Router {
83
87
  * @returns {Router} - Returns the router instance.
84
88
  */
85
89
  delete(path, callback) {
86
- this.util.routeHelper("delete", path, callback);
90
+ this.util.routeHttpMethod("delete", path, callback);
91
+ this.middlewares = null;
87
92
  return this;
88
93
  }
89
94
 
90
95
  /**
91
- * Placeholder method for handling all HTTP methods.
96
+ * Adds a route handler for ALL requests.
97
+ * @param {Function} callback - Callback function to handle the request.
98
+ * @returns {Router} - Returns the router instance.
92
99
  */
93
- all() {}
100
+ all(path, callback) {
101
+ this.util.routeHttpMethod("any", path, callback);
102
+ this.middlewares = null;
103
+ return this;
104
+ }
105
+
106
+ options(path, callback) {
107
+ this.util.routeHttpMethod("options", path, callback);
108
+ this.middlewares = null;
109
+ return this;
110
+ }
94
111
  }
95
112
 
96
113
  module.exports = Router;
@@ -0,0 +1,28 @@
1
+ const { REPL } = require("repl-cli");
2
+ const getInput = require("./getInput");
3
+ const repl = new REPL();
4
+
5
+ const replPrompt = () => {
6
+ repl.use({
7
+ async evaluate(input) {
8
+ switch (input) {
9
+ case "exit()":
10
+ return process.exit(-1);
11
+
12
+ case "exit":
13
+ return process.exit(-1);
14
+ case "quit()":
15
+ return process.exit(-1);
16
+ case "quit":
17
+ return process.exit(-1);
18
+ default:
19
+ const result = await getInput(input);
20
+ console.log(result);
21
+ break;
22
+ }
23
+ },
24
+ });
25
+ repl.start();
26
+ };
27
+
28
+ module.exports = replPrompt;
@@ -0,0 +1,20 @@
1
+ const mongoose = require("mongoose");
2
+ const dotenv = require("dotenv");
3
+ dotenv.config(); // Load environment variables from .env file
4
+
5
+ class Database {
6
+ async connect() {
7
+ try {
8
+ return await mongoose.connect(process.env.DB_HOST); // Connect to the MongoDB database
9
+ } catch (error) {
10
+ console.log("Database not connected"); // Log failure message if connection fails
11
+ }
12
+ }
13
+
14
+ // Method to close database connection
15
+ closeConnection() {
16
+ return mongoose.connection.close(); // Close the MongoDB database connection
17
+ }
18
+ }
19
+
20
+ module.exports = Database;
@@ -0,0 +1,7 @@
1
+ const TinkerNode = require("./");
2
+
3
+ const getInput = async (input) => {
4
+ const cli = new TinkerNode();
5
+ return cli.extractCommand(input);
6
+ };
7
+ module.exports = getInput; // Export the getDbCommandLineArgv function
@@ -0,0 +1,50 @@
1
+ const { getModel } = require("../helpers");
2
+ const Database = require("./db");
3
+
4
+ class TinkerNode extends Database {
5
+ #allowedMethodsRegex = /[^\s{}()\[\]\(\)0-9a-zA-Z',_.:@]/g;
6
+
7
+ sanitizedInput(input) {
8
+ return input.replace(this.#allowedMethodsRegex, "");
9
+ }
10
+
11
+ validatedInput(input) {
12
+ const sanitizedInputData = this.sanitizedInput(input);
13
+ console.log(sanitizedInputData);
14
+ if (sanitizedInputData !== input) {
15
+ // Input contains disallowed characters, reject it
16
+ throw new Error("Input contains disallowed characters.");
17
+ }
18
+
19
+ const data = input.split(".");
20
+ if (data.length <= 1) {
21
+ throw new Error("Invalid Mongoose query:", input);
22
+ }
23
+ const model = data[0];
24
+
25
+ data.splice(0, 1);
26
+
27
+ return { model, methods: data.join(".") };
28
+ }
29
+
30
+ async extractCommand(input) {
31
+ try {
32
+ const { model, methods } = this.validatedInput(input);
33
+ const queryFunction = new Function(
34
+ "model",
35
+ "getModel",
36
+ `
37
+ const modelName = getModel(model)
38
+ return modelName.${methods}
39
+ `
40
+ );
41
+
42
+ this.connect();
43
+ return queryFunction(model, getModel);
44
+ } catch (error) {
45
+ return console.error("Error " + error?.message);
46
+ }
47
+ }
48
+ }
49
+
50
+ module.exports = TinkerNode;
package/src/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  const App = require("./app");
2
2
  const { authenticated, protectedApi } = require("./Auth/protectedRoute");
3
3
  const Auth = require("./Auth");
4
+ const replPrompt = require("./command-line-interface/REPL");
4
5
 
5
6
  const {
6
7
  bcrypt,
@@ -16,7 +17,6 @@ const {
16
17
  rootPath,
17
18
  } = require("./helpers");
18
19
  const FormRequest = require("./request/FormRequest");
19
- const getDbCli = require("./command-line-interface/getDbCliCommand");
20
20
 
21
21
  const app = new App();
22
22
 
@@ -39,6 +39,6 @@ module.exports = {
39
39
  authenticated,
40
40
  apiAuthenticated: protectedApi,
41
41
  Auth,
42
- getDbCli,
43
42
  FormRequest,
43
+ replPrompt,
44
44
  };
@@ -16,6 +16,18 @@ class Util {
16
16
  this.middlewares = middlewares;
17
17
  }
18
18
 
19
+ /**
20
+ * Replaces route parameters enclosed in curly braces with corresponding placeholders.
21
+ * For example, converts "{name}" to ":name".
22
+ *
23
+ * @param {string} path - The path containing route parameters.
24
+ * @returns {string} - The path with route parameters replaced by placeholders.
25
+ */
26
+ replaceRouteParameters(path) {
27
+ const regex = /\{([^}]+)\}/g;
28
+ return path.replace(regex, ":$1");
29
+ }
30
+
19
31
  /**
20
32
  * Sets the middlewares for the route group.
21
33
  * @param {function|array} middlewares - Route middlewares.
@@ -31,8 +43,8 @@ class Util {
31
43
  */
32
44
  resolvePath(path) {
33
45
  return this.prefix
34
- ? `${this.basePath}${this.prefix}${path}`
35
- : `${this.basePath}${path}`;
46
+ ? `${this.basePath}${this.prefix}${this.replaceRouteParameters(path)}`
47
+ : `${this.basePath}${this.replaceRouteParameters(path)}`;
36
48
  }
37
49
 
38
50
  /**
@@ -85,7 +97,7 @@ class Util {
85
97
  * @param {string} path - The route path.
86
98
  * @param {string} callback - The callback function or method name.
87
99
  */
88
- async routeHelper(httpMethod, path, callback) {
100
+ async routeHttpMethod(httpMethod, path, callback) {
89
101
  try {
90
102
  if (this.classController(callback)) {
91
103
  if (this.isMiddleware()) {
@@ -107,7 +119,6 @@ class Util {
107
119
  this.middlewares,
108
120
  asyncHandler(callback),
109
121
  ]);
110
- return (this.middlewares = null);
111
122
  }
112
123
  return this.app[httpMethod](
113
124
  this.resolvePath(path),
@@ -1,77 +0,0 @@
1
- const mongoose = require("mongoose"); // Import Mongoose for MongoDB interactions
2
- const dotenv = require("dotenv"); // Import dotenv for environment variables
3
- const { getModel, bcrypt } = require("../helpers"); // Import helper functions for database operations and password hashing
4
-
5
- class DbCli {
6
- constructor(model) {
7
- dotenv.config(); // Load environment variables from .env file
8
- this.model = getModel(model); // Get the specified model for database operations
9
- this.connection(); // Establish database connection
10
- }
11
-
12
- // Method to establish database connection
13
- async connection() {
14
- try {
15
- const connect = await mongoose.connect(process.env.DB_HOST); // Connect to the MongoDB database
16
- return connect
17
- ? console.log("Database connected Successfully") // Log success message if connected
18
- : console.log("Database not connected"); // Log failure message if connection fails
19
- } catch (error) {
20
- console.log("Database not connected"); // Log failure message if connection fails
21
- }
22
- }
23
-
24
- // Method to close database connection
25
- closeConnection() {
26
- return mongoose.connection.close(); // Close the MongoDB database connection
27
- }
28
-
29
- // Method to retrieve all documents from the model
30
- async all() {
31
- const data = await this.model.find({}); // Find all documents in the model
32
- console.log(data); // Log retrieved data
33
- return this.closeConnection(); // Close database connection
34
- }
35
-
36
- // Method to create a new document in the model
37
- async create(data) {
38
- const obj = {}; // Initialize an empty object to store document fields
39
- const items = data.split(","); // Split the input data into key-value pairs
40
-
41
- // Iterate through each key-value pair
42
- for (let i = 0; i < items.length; i++) {
43
- const objName = items[i].split(":")[0]; // Extract the field name
44
- const objValue = items[i].split(":")[1]; // Extract the field value
45
-
46
- // If the field is a password, hash the value using bcrypt
47
- if (objName === "password") {
48
- obj[objName] = await bcrypt(objValue); // Hash the password value
49
- continue; // Skip to the next iteration
50
- }
51
- obj[objName] = objValue; // Add the field and value to the object
52
- }
53
-
54
- const result = await this.model.create(obj); // Create a new document in the model with the constructed object
55
- console.log(result); // Log the result of the creation operation
56
- return this.closeConnection(); // Close database connection
57
- }
58
-
59
- // Method to find a document by its ID
60
- async findById(id) {
61
- const result = await this.model.findById(id); // Find a document by its ID
62
- console.log(result); // Log the retrieved document
63
- return this.closeConnection(); // Close database connection
64
- }
65
-
66
- // Method to delete a document by its ID
67
- async delete(id) {
68
- const result = await this.model.findByIdAndRemove(id); // Find and remove a document by its ID
69
- console.log(result); // Log the result of the deletion operation
70
- return this.closeConnection(); // Close database connection
71
- }
72
-
73
- // Method for updating documents (not implemented)
74
- // update() {}
75
- }
76
-
77
- module.exports = DbCli; // Export the DbCli class
@@ -1,21 +0,0 @@
1
- const DbCli = require("./dbCli"); // Import DbCli class for interacting with the database
2
-
3
- // Function to extract the command from command line arguments
4
- const getCommand = (command, index = 0) => {
5
- let cmd = command.slice(2); // Extract command arguments, excluding the first two (node and script name)
6
- return `${cmd[0].split(".")[index]}`; // Extract the command from the first argument, splitting by "." and taking the specified index
7
- };
8
-
9
- // Function to extract the argument from command line arguments
10
- const getArg = (command) => command.slice(3)[0]; // Extract the argument from command arguments, starting from the fourth element
11
-
12
- // Function to handle command line arguments related to database operations
13
- const getDbCommandLineArgv = (commandArg) => {
14
- let model = getCommand(commandArg); // Extract the model name from command line arguments
15
- let method = getCommand(commandArg, 1); // Extract the method name (action) from command line arguments
16
- let arg = getArg(commandArg); // Extract the argument (if any) from command line arguments
17
- const db = new DbCli(model); // Instantiate DbCli class with the extracted model name
18
- return arg ? db[method](arg) : db[method](); // Execute the specified method with the argument (if provided), otherwise without argument
19
- };
20
-
21
- module.exports = getDbCommandLineArgv; // Export the getDbCommandLineArgv function