4bnode 1.0.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/index.js ADDED
@@ -0,0 +1,226 @@
1
+ #!/usr/bin/env node
2
+
3
+ import fs from "fs";
4
+ import path from "path";
5
+ import { execSync } from "child_process";
6
+ import { fileURLToPath } from "url";
7
+ import chalk from "chalk";
8
+
9
+ const __filename = fileURLToPath(import.meta.url);
10
+ const __dirname = path.dirname(__filename);
11
+ const skeletonPath = path.join(__dirname, "skeleton");
12
+
13
+ function copyRecursiveSync(src, dest) {
14
+ const exists = fs.existsSync(src);
15
+ const stats = exists && fs.statSync(src);
16
+ const isDirectory = exists && stats.isDirectory();
17
+ if (isDirectory) {
18
+ if (!fs.existsSync(dest)) {
19
+ fs.mkdirSync(dest);
20
+ }
21
+ fs.readdirSync(src).forEach((childItemName) => {
22
+ copyRecursiveSync(
23
+ path.join(src, childItemName),
24
+ path.join(dest, childItemName)
25
+ );
26
+ });
27
+ } else {
28
+ fs.copyFileSync(src, dest);
29
+ }
30
+ }
31
+
32
+ function updatePackageName(destinationPath, projectName) {
33
+ const packageJsonPath = path.join(destinationPath, "package.json");
34
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf8"));
35
+ packageJson.name = projectName;
36
+ fs.writeFileSync(
37
+ packageJsonPath,
38
+ JSON.stringify(packageJson, null, 2),
39
+ "utf8"
40
+ );
41
+ }
42
+
43
+ function createSkeletonApp(projectName) {
44
+ const targetPath = path.resolve(projectName);
45
+ if (!fs.existsSync(targetPath)) {
46
+ fs.mkdirSync(targetPath, { recursive: true });
47
+ }
48
+ copyRecursiveSync(skeletonPath, targetPath);
49
+ updatePackageName(targetPath, projectName);
50
+ console.log(`Node.js skeleton app created successfully in ${projectName}.`);
51
+
52
+ // Install dependencies
53
+ execSync("npm install", { stdio: "inherit", cwd: targetPath });
54
+ console.log("Dependencies installed successfully.");
55
+ }
56
+
57
+ function checkModelsExist() {
58
+ const projectRoot = process.cwd();
59
+ const modelsDir = path.join(projectRoot, "src", "models");
60
+ return fs.existsSync(modelsDir) && fs.readdirSync(modelsDir).length > 0;
61
+ }
62
+
63
+ function checkRoutesDir() {
64
+ const projectRoot = process.cwd();
65
+ const routesDir = path.join(projectRoot, "src", "routes");
66
+ return fs.existsSync(routesDir);
67
+ }
68
+
69
+ function checkMongoConfig() {
70
+ const projectRoot = process.cwd();
71
+ const envPath = path.join(projectRoot, ".env.development");
72
+ return (
73
+ fs.existsSync(envPath) &&
74
+ fs.readFileSync(envPath, "utf8").includes("MONGO_URI")
75
+ );
76
+ }
77
+
78
+ function showHelp() {
79
+ console.log(
80
+ chalk.green(`
81
+ Usage: ${chalk.bold("node-app <command> [options]")}
82
+
83
+ Commands:
84
+ ${chalk.blue(
85
+ "init <projectName>"
86
+ )} Create a new Node.js project with the given name.
87
+ ${chalk.blue(
88
+ "add-api <endpointName>"
89
+ )} Add a new API endpoint with the given name.
90
+ ${chalk.blue("add-mongo")} Configure MongoDB for the project.
91
+ ${chalk.blue(
92
+ "add-socket"
93
+ )} Add Socket.IO support to the project.
94
+ ${chalk.blue(
95
+ "add-websocket"
96
+ )} Add WebSocket support to the project.
97
+ ${chalk.blue(
98
+ "add-mongo-schema <schemaName>"
99
+ )} Add a new MongoDB schema with the given name.
100
+ ${chalk.blue("add-login")} Add a login route to the project.
101
+ ${chalk.blue("add-mongo-insert")} Add an insert route for MongoDB.
102
+ ${chalk.blue("add-mongo-update")} Add an update route for MongoDB.
103
+ ${chalk.blue("add-mongo-read")} Add a read route for MongoDB.
104
+ ${chalk.blue("add-mongo-delete")} Add a delete route for MongoDB.
105
+
106
+ Options:
107
+ ${chalk.blue("-h, --help")} Show this help message.
108
+ `)
109
+ );
110
+ }
111
+
112
+ const args = process.argv.slice(2);
113
+ if (args.length < 1 || args.includes("-h") || args.includes("--help")) {
114
+ showHelp();
115
+ process.exit(0);
116
+ }
117
+
118
+ const command = args[0];
119
+ const param = args[1];
120
+
121
+ if (command === "init") {
122
+ if (!param) {
123
+ console.error(chalk.red("Usage: node-app init <projectName>"));
124
+ process.exit(1);
125
+ }
126
+ createSkeletonApp(param);
127
+ } else if (command === "add-api") {
128
+ if (!param) {
129
+ console.error(chalk.red("Usage: node-app add-api <endpointName>"));
130
+ process.exit(1);
131
+ }
132
+ execSync(`node ${path.join(__dirname, "add-api.js")} ${param}`, {
133
+ stdio: "inherit",
134
+ });
135
+ } else if (command === "add-mongo") {
136
+ execSync(`node ${path.join(__dirname, "add-mongo.js")}`, {
137
+ stdio: "inherit",
138
+ });
139
+ } else if (command === "add-socket") {
140
+ execSync(`node ${path.join(__dirname, "add-socket.js")}`, {
141
+ stdio: "inherit",
142
+ });
143
+ } else if (command === "add-websocket") {
144
+ execSync(`node ${path.join(__dirname, "add-websocket.js")}`, {
145
+ stdio: "inherit",
146
+ });
147
+ } else if (command === "add-mongo-schema") {
148
+ if (!param) {
149
+ console.error(chalk.red("Usage: node-app add-mongo-schema <schemaName>"));
150
+ process.exit(1);
151
+ }
152
+ if (!checkMongoConfig()) {
153
+ console.error(
154
+ chalk.red(
155
+ "MongoDB is not configured. Please run 'node-app add-mongo' first."
156
+ )
157
+ );
158
+ process.exit(1);
159
+ }
160
+ execSync(`node ${path.join(__dirname, "add-mongo-schema.js")} ${param}`, {
161
+ stdio: "inherit",
162
+ });
163
+ } else if (command === "add-login") {
164
+ if (!checkRoutesDir()) {
165
+ console.error(chalk.red("No routes directory found in src/routes"));
166
+ process.exit(1);
167
+ }
168
+ execSync(`node ${path.join(__dirname, "add-login.js")}`, {
169
+ stdio: "inherit",
170
+ });
171
+ } else if (command === "add-mongo-insert") {
172
+ if (!checkRoutesDir()) {
173
+ console.error(chalk.red("No routes directory found in src/routes"));
174
+ process.exit(1);
175
+ }
176
+ if (!checkModelsExist()) {
177
+ console.error(chalk.red("No model files found in src/models"));
178
+ process.exit(1);
179
+ }
180
+ execSync(`node ${path.join(__dirname, "add-mongo-insert.js")}`, {
181
+ stdio: "inherit",
182
+ });
183
+ } else if (command === "add-mongo-update") {
184
+ if (!checkRoutesDir()) {
185
+ console.error(chalk.red("No routes directory found in src/routes"));
186
+ process.exit(1);
187
+ }
188
+ if (!checkModelsExist()) {
189
+ console.error(chalk.red("No model files found in src/models"));
190
+ process.exit(1);
191
+ }
192
+ execSync(`node ${path.join(__dirname, "add-mongo-update.js")}`, {
193
+ stdio: "inherit",
194
+ });
195
+ } else if (command === "add-mongo-read") {
196
+ if (!checkRoutesDir()) {
197
+ console.error(chalk.red("No routes directory found in src/routes"));
198
+ process.exit(1);
199
+ }
200
+ if (!checkModelsExist()) {
201
+ console.error(chalk.red("No model files found in src/models"));
202
+ process.exit(1);
203
+ }
204
+ execSync(`node ${path.join(__dirname, "add-mongo-read.js")}`, {
205
+ stdio: "inherit",
206
+ });
207
+ } else if (command === "add-mongo-delete") {
208
+ if (!checkRoutesDir()) {
209
+ console.error(chalk.red("No routes directory found in src/routes"));
210
+ process.exit(1);
211
+ }
212
+ if (!checkModelsExist()) {
213
+ console.error(chalk.red("No model files found in src/models"));
214
+ process.exit(1);
215
+ }
216
+ execSync(`node ${path.join(__dirname, "add-mongo-delete.js")}`, {
217
+ stdio: "inherit",
218
+ });
219
+ } else if (command === "add-serialport") {
220
+ execSync(`node ${path.join(__dirname, "add-serialport.js")}`, {
221
+ stdio: "inherit",
222
+ });
223
+ } else {
224
+ console.error(chalk.red("Unknown command. Use -h or --help for help."));
225
+ process.exit(1);
226
+ }
package/package.json ADDED
@@ -0,0 +1,40 @@
1
+ {
2
+ "name": "4bnode",
3
+ "version": "1.0.0",
4
+ "description": "A CLI tool to generate a Node.js app by 4Brains Technologies",
5
+ "main": "index.js",
6
+ "type": "module",
7
+ "bin": {
8
+ "4bnode": "index.js",
9
+ "add-api": "add-api.js",
10
+ "add-mongo": "add-mongo.js",
11
+ "add-socket": "add-socket.js",
12
+ "add-websocket": "add-websocket.js",
13
+ "add-mongo-schema": "add-mongo-schema.js",
14
+ "add-login": "add-login.js",
15
+ "add-mongo-insert": "add-mongo-insert.js",
16
+ "add-mongo-update": "add-mongo-update.js",
17
+ "add-mongo-read": "add-mongo-read.js",
18
+ "add-mongo-delete": "add-mongo-delete.js"
19
+ },
20
+ "scripts": {
21
+ "test": "echo \"Error: no test specified\" && exit 1"
22
+ },
23
+ "repository": {
24
+ "type": "git",
25
+ "url": "https://github.com/pawan-4brains/4brains-node-generator"
26
+ },
27
+ "keywords": [
28
+ "node",
29
+ "generator",
30
+ "express",
31
+ "express-generator",
32
+ "node.js",
33
+ "Node.js skeleton"
34
+ ],
35
+ "author": "4Brains",
36
+ "license": "ISC",
37
+ "dependencies": {
38
+ "chalk": "^5.3.0"
39
+ }
40
+ }
@@ -0,0 +1 @@
1
+ PORT=3000
@@ -0,0 +1 @@
1
+ PORT=3000
@@ -0,0 +1,45 @@
1
+ import express from "express";
2
+ import dotenv from "dotenv";
3
+ import bodyParser from "body-parser";
4
+ import path from "path";
5
+ import cors from "cors";
6
+ import os from "os";
7
+
8
+ const env = process.env.NODE_ENV || "development";
9
+ dotenv.config({ path: `.env.${env}` });
10
+
11
+ const app = express();
12
+ const port = process.env.PORT || 3000;
13
+
14
+ // Middleware
15
+ app.use(bodyParser.json({ limit: "50mb" }));
16
+ app.use(bodyParser.urlencoded({ extended: true, limit: "50mb" }));
17
+ app.use(cors({ origin: "*" }));
18
+
19
+ // Serve static files from the public directory
20
+ const __dirname = path.resolve();
21
+ app.use(express.static(path.join(__dirname, "public")));
22
+
23
+ // Get local network IP address
24
+ function getLocalNetworkIp() {
25
+ const interfaces = os.networkInterfaces();
26
+ for (const name of Object.keys(interfaces)) {
27
+ for (const iface of interfaces[name]) {
28
+ if (iface.family === "IPv4" && !iface.internal) {
29
+ return iface.address;
30
+ }
31
+ }
32
+ }
33
+ return null;
34
+ }
35
+
36
+ // Start server
37
+ app.listen(port, () => {
38
+ const localIp = getLocalNetworkIp();
39
+ console.log(`App is running on http://localhost:${port}`);
40
+ if (localIp) {
41
+ console.log(
42
+ `App is also accessible on your local network at http://${localIp}:${port}`
43
+ );
44
+ }
45
+ });
@@ -0,0 +1,19 @@
1
+ {
2
+ "name": "node-skeleton-app",
3
+ "version": "1.0.0",
4
+ "main": "index.js",
5
+ "type": "module",
6
+ "scripts": {
7
+ "start": "node index.js",
8
+ "dev": "nodemon index.js"
9
+ },
10
+ "dependencies": {
11
+ "express": "^4.19.2",
12
+ "dotenv": "^16.4.5",
13
+ "body-parser": "^1.20.2",
14
+ "cors": "^2.8.5"
15
+ },
16
+ "devDependencies": {
17
+ "nodemon": "^3.1.3"
18
+ }
19
+ }
@@ -0,0 +1,90 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
+ <title>Welcome to 4Brains Node App</title>
7
+ <style>
8
+ body {
9
+ margin: 0;
10
+ font-family: "Courier New", Courier, monospace;
11
+ background-color: #121212;
12
+ color: #ffffff;
13
+ display: flex;
14
+ justify-content: center;
15
+ align-items: center;
16
+ height: 100vh;
17
+ flex-direction: column;
18
+ }
19
+ .container {
20
+ text-align: center;
21
+ background: #1e1e1e;
22
+ padding: 2rem 3rem;
23
+ border-radius: 12px;
24
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
25
+ margin-bottom: 2rem;
26
+ }
27
+ h1 {
28
+ font-size: 2.5rem;
29
+ margin-bottom: 1rem;
30
+ }
31
+ p {
32
+ font-size: 1.2rem;
33
+ margin-bottom: 2rem;
34
+ color: #bbbbbb;
35
+ }
36
+ a {
37
+ color: #ffffff;
38
+ text-decoration: none;
39
+ background-color: #1e90ff;
40
+ padding: 0.5rem 1.5rem;
41
+ border-radius: 4px;
42
+ transition: background-color 0.3s, transform 0.3s;
43
+ }
44
+ a:hover {
45
+ background-color: #0a74da;
46
+ transform: scale(1.05);
47
+ }
48
+ .console {
49
+ font-family: "Courier New", Courier, monospace;
50
+ background: #000000;
51
+ color: #33ff33;
52
+ padding: 1rem 1rem 2rem 1rem;
53
+ border-radius: 8px;
54
+ margin-bottom: 1.5rem;
55
+ text-align: center;
56
+ line-height: 1.5;
57
+ white-space: preserve-breaks;
58
+ }
59
+ .footer {
60
+ text-align: center;
61
+ color: #bbbbbb;
62
+ font-size: 0.9rem;
63
+ }
64
+ .footer img {
65
+ width: 200px;
66
+ margin-bottom: 0.5rem;
67
+ }
68
+ </style>
69
+ </head>
70
+ <body>
71
+ <div class="container">
72
+ <div class="console">
73
+ /----------------------------------\ <br />
74
+ | 4Brains Node Generator | <br />
75
+ \----------------------------------/
76
+ </div>
77
+ <h1>Welcome to 4Brains Node App</h1>
78
+ <p>Your Node.js app is up and running!</p>
79
+ <a
80
+ href="https://github.com/pawan-4brains/4brains-node-generator"
81
+ target="_blank"
82
+ >Learn More</a
83
+ >
84
+ </div>
85
+ <div class="footer">
86
+ <img src="https://cdn.4brains.in/logo.png" alt="4Brains Logo" />
87
+ <p>© 2023 4Brains Technologies Pvt Ltd. All rights reserved.</p>
88
+ </div>
89
+ </body>
90
+ </html>
@@ -0,0 +1,21 @@
1
+ import passport from 'passport';
2
+ import { Strategy as JwtStrategy, ExtractJwt } from 'passport-jwt';
3
+ import mongoose from 'mongoose';
4
+ import User from '../models/User.js'; // Adjust the path to your user model
5
+
6
+ const opts = {};
7
+ opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
8
+ opts.secretOrKey = process.env.JWT_SECRET;
9
+
10
+ passport.use(new JwtStrategy(opts, (jwt_payload, done) => {
11
+ User.findById(jwt_payload.id)
12
+ .then(user => {
13
+ if (user) {
14
+ return done(null, user);
15
+ }
16
+ return done(null, false);
17
+ })
18
+ .catch(err => console.error(err));
19
+ }));
20
+
21
+ export default passport;
package/src/db.js ADDED
@@ -0,0 +1,13 @@
1
+ import mongoose from 'mongoose';
2
+
3
+ const connectDB = async () => {
4
+ try {
5
+ const conn = await mongoose.connect(process.env.MONGO_URI);
6
+ console.log(`MongoDB connected: ${conn.connection.host}`);
7
+ } catch (err) {
8
+ console.error(err);
9
+ process.exit(1);
10
+ }
11
+ };
12
+
13
+ export default connectDB;
@@ -0,0 +1 @@
1
+ PORT=3000
@@ -0,0 +1 @@
1
+ PORT=3000
@@ -0,0 +1,82 @@
1
+ import { WebSocketServer } from 'ws';
2
+ import http from 'http';
3
+ import express from "express";
4
+ import dotenv from "dotenv";
5
+ import bodyParser from "body-parser";
6
+ import path from "path";
7
+ import cors from "cors";
8
+ import os from "os";
9
+
10
+ const env = process.env.NODE_ENV || "development";
11
+ dotenv.config({ path: `.env.${env}` });
12
+
13
+ const app = express();
14
+ const port = process.env.PORT || 3000;
15
+
16
+ // Middleware
17
+
18
+ const server = http.createServer(app);
19
+ const wsServer = new WebSocketServer({ server });
20
+ console.log(`WebSocket server is running on the same port as the server (${port})`);
21
+
22
+ wsServer.on('connection', (ws) => {
23
+ console.log('A client connected');
24
+
25
+ ws.on('message', (message) => {
26
+ try {
27
+ const parsedMessage = JSON.parse(message);
28
+ console.log('Received:', parsedMessage);
29
+
30
+ // Broadcast to all clients except sender
31
+ wsServer.clients.forEach((client) => {
32
+ if (client !== ws && client.readyState === ws.OPEN) {
33
+ client.send(JSON.stringify(parsedMessage));
34
+ }
35
+ });
36
+ } catch (error) {
37
+ console.error('Invalid message format:', error);
38
+ }
39
+ });
40
+
41
+ ws.on('close', () => {
42
+ console.log('Client disconnected');
43
+ });
44
+ });
45
+
46
+ app.use((req, res, next) => {
47
+ req.wss = wsServer;
48
+ next();
49
+ });
50
+ app.use(bodyParser.json({ limit: "50mb" }));
51
+ app.use(bodyParser.urlencoded({ extended: true, limit: "50mb" }));
52
+ app.use(cors({ origin: "*" }));
53
+
54
+ // Serve static files from the public directory
55
+ const __dirname = path.resolve();
56
+ app.use(express.static(path.join(__dirname, "public")));
57
+
58
+ // Get local network IP address
59
+ function getLocalNetworkIp() {
60
+ const interfaces = os.networkInterfaces();
61
+ for (const name of Object.keys(interfaces)) {
62
+ for (const iface of interfaces[name]) {
63
+ if (iface.family === "IPv4" && !iface.internal) {
64
+ return iface.address;
65
+ }
66
+ }
67
+ }
68
+ return null;
69
+ }
70
+
71
+ // Start server
72
+
73
+
74
+ server.listen(port, () => {
75
+ const localIp = getLocalNetworkIp();
76
+ console.log(`App is running on http://localhost:${port}`);
77
+ if (localIp) {
78
+ console.log(
79
+ `App is also accessible on your local network at http://${localIp}:${port}`
80
+ );
81
+ }
82
+ });