@madhusha_99/exp-gen 1.1.3 → 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/README.md +2 -2
- package/bin/script.js +3 -4
- package/bin/script.js.map +1 -1
- package/package.json +2 -1
- package/src/templates/js/mysql/app.js +42 -0
- package/src/templates/js/mysql/configs/config.js +17 -0
- package/src/templates/js/mysql/configs/db.js +50 -0
- package/src/templates/js/mysql/controllers/auth.controller.js +83 -0
- package/src/templates/js/mysql/controllers/user.controller.js +27 -0
- package/src/templates/js/mysql/default.env +9 -0
- package/src/templates/js/mysql/middlewares/auth.middleware.js +64 -0
- package/src/templates/js/mysql/models/user.model.js +22 -0
- package/src/templates/js/mysql/package-lock.json +4386 -0
- package/src/templates/js/mysql/package.json +29 -0
- package/src/templates/js/mysql/repositories/user.repository.js +84 -0
- package/src/templates/js/mysql/routes/auth.route.js +9 -0
- package/src/templates/js/mysql/routes/user.route.js +24 -0
- package/src/templates/js/mysql/services/user.service.js +50 -0
- package/src/templates/js/mysql/utils/asyncHandler.js +5 -0
- package/src/templates/js/mysql/utils/response.js +13 -0
- package/src/templates/js/mysql/.gitkeep +0 -0
package/README.md
CHANGED
|
@@ -35,8 +35,8 @@ Run `exp` in your terminal. The interactive CLI (powered by `@clack/prompts`) wi
|
|
|
35
35
|
- **Project Name:** Enter your project folder name (e.g., `my-api`).
|
|
36
36
|
- **Language:** Choose between **TypeScript** (Recommended) or **JavaScript**.
|
|
37
37
|
- **Database:** Select your preferred database.
|
|
38
|
-
|
|
39
|
-
|
|
38
|
+
- _Currently Supported:_ **MongoDB** (via Mongoose) and **PostgreSQL** (only for JavaScript projects).
|
|
39
|
+
- _Coming Soon:_ MySQL, PostgreSQL (Prisma), and SQLite.
|
|
40
40
|
- **Install Dependencies:** Choose `Yes` to let the CLI run `npm install` for you automatically.
|
|
41
41
|
|
|
42
42
|
### 2. Navigate and Run
|
package/bin/script.js
CHANGED
|
@@ -79,11 +79,10 @@ async function main() {
|
|
|
79
79
|
label: pc.green("PostgreSQL"),
|
|
80
80
|
hint: "via PostgreSQL (Available)",
|
|
81
81
|
},
|
|
82
|
-
// 🚧 Coming Soon
|
|
83
82
|
{
|
|
84
83
|
value: "mysql",
|
|
85
84
|
label: pc.yellow("MySQL"),
|
|
86
|
-
hint: pc.dim("
|
|
85
|
+
hint: pc.dim("via MySQL (Available)"),
|
|
87
86
|
},
|
|
88
87
|
{
|
|
89
88
|
value: "sqlite",
|
|
@@ -108,10 +107,10 @@ async function main() {
|
|
|
108
107
|
},
|
|
109
108
|
});
|
|
110
109
|
//Stop if user selected a "coming soon" DB
|
|
111
|
-
const comingSoonDBs = ["
|
|
110
|
+
const comingSoonDBs = ["sqlite"];
|
|
112
111
|
if (comingSoonDBs.includes(project.db)) {
|
|
113
112
|
p.cancel(pc.yellow(`🚧 ${project.db.toUpperCase()} support is coming soon!\n\n` +
|
|
114
|
-
pc.dim("Currently only MongoDB and PostgreSQL (only for js project) supported.\n") +
|
|
113
|
+
pc.dim("Currently only MongoDB, MySQL and PostgreSQL (only for js project) supported.\n") +
|
|
115
114
|
pc.dim("Stay tuned for future updates 🚀")));
|
|
116
115
|
process.exit(0);
|
|
117
116
|
}
|
package/bin/script.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"script.js","sourceRoot":"","sources":["../../bin/script.ts"],"names":[],"mappings":";AAEA,OAAO,KAAK,CAAC,MAAM,gBAAgB,CAAC;AACpC,OAAO,EAAE,MAAM,YAAY,CAAC;AAC5B,OAAO,UAAU,MAAM,aAAa,CAAC;AACrC,OAAO,EAAE,MAAM,aAAa,CAAC;AAC7B,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,aAAa,EAAE,MAAM,KAAK,CAAC;AAEpC,OAAO,eAAe,MAAM,sBAAsB,CAAC;AAEnD,MAAM,UAAU,GAAG,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,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AAE,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,CAAC;MAC5C,EAAE,CAAC,IAAI,CAAC,eAAe,CAAC,IAAI,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE,EAC9D,uBAAuB,CACxB,CAAC;IAEF,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,YAAY,CAAC;IAC9B,EAAE,CAAC,IAAI,CAAC,MAAM,OAAO,CAAC,IAAI,EAAE,CAAC;IAE7B,OAAO,CAAC,OAAO;QACb,CAAC,CAAC,EAAE,CAAC,IAAI,CAAC,aAAa,CAAC;QACxB,CAAC,CAAC,EAAE,CAAC,IAAI,CAAC,4BAA4B,CAC1C;;IAEE,EAAE,CAAC,KAAK,CAAC,kBAAkB,CAAC,EAAE,CAAC,CAAC;AACpC,CAAC;AAED,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE;IACnB,CAAC,CAAC,MAAM,CAAC,EAAE,CAAC,GAAG,CAAC,UAAU,GAAG,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC;IAE1C,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC,CAAC,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@madhusha_99/exp-gen",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.2.0",
|
|
4
4
|
"description": "This is a very simple and small generator for creating Express.js projects with TypeScript or Javascript. You can use it to quickly start a new API project.",
|
|
5
5
|
"main": "bin/script.js",
|
|
6
6
|
"bin": {
|
|
@@ -16,6 +16,7 @@
|
|
|
16
16
|
"src/templates/",
|
|
17
17
|
"README.md"
|
|
18
18
|
],
|
|
19
|
+
"readmeFilename": "README.md",
|
|
19
20
|
"author": "Madhusha Prasad <madushaprasad21@gmail.com> (https://github.com/MadhushaPrasad)",
|
|
20
21
|
"license": "MIT",
|
|
21
22
|
"keywords": [
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import express from "express";
|
|
2
|
+
import morgan from "morgan";
|
|
3
|
+
import createError from "http-errors";
|
|
4
|
+
import cors from "cors";
|
|
5
|
+
import apiRoutes from "./routes/user.route.js";
|
|
6
|
+
import authRoutes from "./routes/auth.route.js";
|
|
7
|
+
import { connectDB } from "./configs/db.js";
|
|
8
|
+
import { ensureUsersTable } from "./models/user.model.js";
|
|
9
|
+
|
|
10
|
+
await connectDB();
|
|
11
|
+
await ensureUsersTable();
|
|
12
|
+
|
|
13
|
+
const app = express();
|
|
14
|
+
|
|
15
|
+
// Middlewares
|
|
16
|
+
app.use(cors());
|
|
17
|
+
app.use(express.json());
|
|
18
|
+
app.use(express.urlencoded({ extended: true }));
|
|
19
|
+
app.use(morgan("dev"));
|
|
20
|
+
|
|
21
|
+
// Routes
|
|
22
|
+
app.get("/", (req, res) => res.json({ message: "API is running 🚀" }));
|
|
23
|
+
app.use("/api", apiRoutes); // user routes
|
|
24
|
+
app.use("/api/auth", authRoutes); // login route
|
|
25
|
+
|
|
26
|
+
// 404 handler
|
|
27
|
+
app.use((req, res, next) => {
|
|
28
|
+
next(createError.NotFound());
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
// Global error handler
|
|
32
|
+
app.use((err, req, res) => {
|
|
33
|
+
res.status(err.status || 500).json({
|
|
34
|
+
success: false,
|
|
35
|
+
message: err.message || "Internal Server Error",
|
|
36
|
+
});
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
const PORT = process.env.PORT || 3000;
|
|
40
|
+
app.listen(PORT, () =>
|
|
41
|
+
console.log(`🚀 Server running @ http://localhost:${PORT}`)
|
|
42
|
+
);
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import dotenv from "dotenv";
|
|
2
|
+
|
|
3
|
+
dotenv.config();
|
|
4
|
+
|
|
5
|
+
const config = {
|
|
6
|
+
db: {
|
|
7
|
+
host: process.env.DB_HOST || "localhost",
|
|
8
|
+
user: process.env.DB_USER || "root",
|
|
9
|
+
password: process.env.DB_PASSWORD || "",
|
|
10
|
+
database: process.env.DB_DATABASE || "",
|
|
11
|
+
connectionLimit: parseInt(process.env.DB_CONNECTION_LIMIT || "10", 10),
|
|
12
|
+
},
|
|
13
|
+
port: parseInt(process.env.PORT || "3000", 10),
|
|
14
|
+
listPerPage: parseInt(process.env.LIST_PER_PAGE || "50", 10),
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
export default config;
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import mysql from "mysql2/promise";
|
|
2
|
+
import config from "../configs/config.js";
|
|
3
|
+
|
|
4
|
+
let pool;
|
|
5
|
+
|
|
6
|
+
export const connectDB = async () => {
|
|
7
|
+
try {
|
|
8
|
+
pool = mysql.createPool({
|
|
9
|
+
host: config.db.host,
|
|
10
|
+
user: config.db.user,
|
|
11
|
+
password: config.db.password,
|
|
12
|
+
database: config.db.database,
|
|
13
|
+
waitForConnections: true,
|
|
14
|
+
connectionLimit: config.db.connectionLimit || 10,
|
|
15
|
+
queueLimit: 0,
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
// Simple test query
|
|
19
|
+
const connection = await pool.getConnection();
|
|
20
|
+
try {
|
|
21
|
+
const [rows] = await connection.query("SELECT 1 + 1 AS solution");
|
|
22
|
+
console.log("The solution is:", rows[0].solution);
|
|
23
|
+
} finally {
|
|
24
|
+
connection.release();
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
console.log(`✅ MysqlDB Connected: ${config.db.host}`);
|
|
28
|
+
} catch (error) {
|
|
29
|
+
console.error("❌ MysqlDB connection error:", error.message);
|
|
30
|
+
process.exit(1);
|
|
31
|
+
}
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
export const getPool = () => {
|
|
35
|
+
if (!pool) {
|
|
36
|
+
throw new Error("Pool not initialized. Call connectDB() first.");
|
|
37
|
+
}
|
|
38
|
+
return pool;
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
export const query = async (sql, params = []) => {
|
|
42
|
+
const p = getPool();
|
|
43
|
+
try {
|
|
44
|
+
const [rows, fields] = await p.query(sql, params);
|
|
45
|
+
return rows;
|
|
46
|
+
} catch (error) {
|
|
47
|
+
console.error("❌ Query error:", error.message);
|
|
48
|
+
throw error;
|
|
49
|
+
}
|
|
50
|
+
};
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import asyncHandler from "../utils/asyncHandler.js";
|
|
2
|
+
import jwt from "jsonwebtoken";
|
|
3
|
+
import bcrypt from "bcryptjs";
|
|
4
|
+
import { successResponse, errorResponse } from "../utils/response.js";
|
|
5
|
+
import * as userRepo from "../repositories/user.repository.js";
|
|
6
|
+
|
|
7
|
+
export const login = asyncHandler(async (req, res) => {
|
|
8
|
+
try {
|
|
9
|
+
const { email, password } = req.body;
|
|
10
|
+
|
|
11
|
+
if (!email || !password) {
|
|
12
|
+
return res
|
|
13
|
+
.status(400)
|
|
14
|
+
.json(errorResponse({ status: 400 }, "Email and password required"));
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const user = await userRepo.getUserByEmail(email);
|
|
18
|
+
if (!user) {
|
|
19
|
+
return res
|
|
20
|
+
.status(401)
|
|
21
|
+
.json(errorResponse({ status: 401 }, "Invalid credentials"));
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const isMatch = await bcrypt.compare(password, user.password);
|
|
25
|
+
if (!isMatch) {
|
|
26
|
+
return res
|
|
27
|
+
.status(401)
|
|
28
|
+
.json(errorResponse({ status: 401 }, "Invalid credentials"));
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const token = jwt.sign(
|
|
32
|
+
{ id: user.id, email: user.email },
|
|
33
|
+
process.env.JWT_SECRET,
|
|
34
|
+
{ expiresIn: process.env.JWT_EXPIRES_IN || "1d" }
|
|
35
|
+
);
|
|
36
|
+
|
|
37
|
+
res.json(successResponse({ token }, "Login successful"));
|
|
38
|
+
} catch (error) {
|
|
39
|
+
res.status(500).json(errorResponse(error, "Login failed"));
|
|
40
|
+
}
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
export const signup = asyncHandler(async (req, res) => {
|
|
44
|
+
try {
|
|
45
|
+
const { name, email, password, age } = req.body;
|
|
46
|
+
|
|
47
|
+
if (!name || !email || !password) {
|
|
48
|
+
return res
|
|
49
|
+
.status(400)
|
|
50
|
+
.json(
|
|
51
|
+
errorResponse({ status: 400 }, "Name, email, and password required")
|
|
52
|
+
);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const existingUser = await userRepo.getUserByEmail(email);
|
|
56
|
+
if (existingUser) {
|
|
57
|
+
return res
|
|
58
|
+
.status(400)
|
|
59
|
+
.json(errorResponse({ status: 400 }, "User already exists"));
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const hashedPassword = await bcrypt.hash(password, 10);
|
|
63
|
+
|
|
64
|
+
const newUser = await userRepo.createUser({
|
|
65
|
+
name,
|
|
66
|
+
email,
|
|
67
|
+
password: hashedPassword,
|
|
68
|
+
age: age || 0,
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
const token = jwt.sign(
|
|
72
|
+
{ id: newUser.id, email: newUser.email },
|
|
73
|
+
process.env.JWT_SECRET,
|
|
74
|
+
{ expiresIn: process.env.JWT_EXPIRES_IN || "1d" }
|
|
75
|
+
);
|
|
76
|
+
|
|
77
|
+
res
|
|
78
|
+
.status(201)
|
|
79
|
+
.json(successResponse({ token, user: newUser }, "Signup successful"));
|
|
80
|
+
} catch (error) {
|
|
81
|
+
res.status(500).json(errorResponse(error, "Signup failed"));
|
|
82
|
+
}
|
|
83
|
+
});
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import * as userService from "../services/user.service.js";
|
|
2
|
+
import asyncHandler from "../utils/asyncHandler.js";
|
|
3
|
+
|
|
4
|
+
export const getUsers = asyncHandler(async (req, res) => {
|
|
5
|
+
const result = await userService.getUsers();
|
|
6
|
+
res.status(result.status).json(result);
|
|
7
|
+
});
|
|
8
|
+
|
|
9
|
+
export const getUser = asyncHandler(async (req, res) => {
|
|
10
|
+
const result = await userService.getUser(req.params.id);
|
|
11
|
+
res.status(result.status).json(result);
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
export const createUser = asyncHandler(async (req, res) => {
|
|
15
|
+
const result = await userService.createNewUser(req.body);
|
|
16
|
+
res.status(result.status).json(result);
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
export const updateUser = asyncHandler(async (req, res) => {
|
|
20
|
+
const result = await userService.updateExistingUser(req.params.id, req.body);
|
|
21
|
+
res.status(result.status).json(result);
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
export const deleteUser = asyncHandler(async (req, res) => {
|
|
25
|
+
const result = await userService.deleteExistingUser(req.params.id);
|
|
26
|
+
res.status(result.status).json(result);
|
|
27
|
+
});
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Auth middleware to protect routes using JWT
|
|
3
|
+
*
|
|
4
|
+
* How to use:
|
|
5
|
+
* 1. Generate a JWT token after user login using `jwt.sign(payload, JWT_SECRET, { expiresIn })`.
|
|
6
|
+
* 2. Send the token in the request headers: Authorization: Bearer <token>
|
|
7
|
+
* 3. Add this middleware to routes you want to protect:
|
|
8
|
+
* router.get('/protected', protect, protectedController)
|
|
9
|
+
* 4. Inside your controller, `req.user` will have the decoded user info
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import jwt from "jsonwebtoken";
|
|
13
|
+
import { errorResponse } from "../utils/response.js";
|
|
14
|
+
|
|
15
|
+
export const protect = (req, res, next) => {
|
|
16
|
+
try {
|
|
17
|
+
const authHeader = req.headers.authorization;
|
|
18
|
+
|
|
19
|
+
if (!authHeader || !authHeader.startsWith("Bearer ")) {
|
|
20
|
+
return res
|
|
21
|
+
.status(401)
|
|
22
|
+
.json(
|
|
23
|
+
errorResponse(
|
|
24
|
+
{ status: 401 },
|
|
25
|
+
"Authorization token missing or malformed"
|
|
26
|
+
)
|
|
27
|
+
);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// Get token from headers
|
|
31
|
+
const token = authHeader.split(" ")[1];
|
|
32
|
+
|
|
33
|
+
if (!token) {
|
|
34
|
+
return res
|
|
35
|
+
.status(401)
|
|
36
|
+
.json(errorResponse({ status: 401 }, "Not authorized, token missing"));
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// Verify token
|
|
40
|
+
let decoded;
|
|
41
|
+
try {
|
|
42
|
+
decoded = jwt.verify(token, process.env.JWT_SECRET);
|
|
43
|
+
} catch (err) {
|
|
44
|
+
if (err.name === "TokenExpiredError") {
|
|
45
|
+
return res
|
|
46
|
+
.status(401)
|
|
47
|
+
.json(errorResponse({ status: 401 }, "Token expired"));
|
|
48
|
+
}
|
|
49
|
+
return res
|
|
50
|
+
.status(401)
|
|
51
|
+
.json(errorResponse({ status: 401 }, "Unauthorized: Invalid token"));
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// Attach decoded user info to request
|
|
55
|
+
req.user = decoded;
|
|
56
|
+
|
|
57
|
+
next();
|
|
58
|
+
} catch (err) {
|
|
59
|
+
// Catch any unexpected errors
|
|
60
|
+
return res
|
|
61
|
+
.status(500)
|
|
62
|
+
.json(errorResponse({ status: 500 }, "Server error: " + err.message));
|
|
63
|
+
}
|
|
64
|
+
};
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { query } from "../configs/db.js";
|
|
2
|
+
|
|
3
|
+
export const ensureUsersTable = async () => {
|
|
4
|
+
const sql = `
|
|
5
|
+
CREATE TABLE IF NOT EXISTS users (
|
|
6
|
+
id INT AUTO_INCREMENT PRIMARY KEY,
|
|
7
|
+
name VARCHAR(255) NOT NULL,
|
|
8
|
+
email VARCHAR(255) NOT NULL UNIQUE,
|
|
9
|
+
password VARCHAR(255) NOT NULL,
|
|
10
|
+
age INT DEFAULT 0,
|
|
11
|
+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
12
|
+
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
|
|
13
|
+
) ENGINE=InnoDB;
|
|
14
|
+
`;
|
|
15
|
+
try {
|
|
16
|
+
await query(sql);
|
|
17
|
+
console.log("✅ Users table ensured");
|
|
18
|
+
} catch (error) {
|
|
19
|
+
console.error("❌ Error ensuring users table:", error.message);
|
|
20
|
+
throw error;
|
|
21
|
+
}
|
|
22
|
+
};
|