@madhusha_99/exp-gen 1.3.0 → 1.5.1

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.
Files changed (30) hide show
  1. package/README.md +253 -37
  2. package/bin/assets/Regex.gif +0 -0
  3. package/bin/assets/RegexWeb.png +0 -0
  4. package/bin/assets/Scaffold.gif +0 -0
  5. package/bin/copyTemplates.js +1 -0
  6. package/bin/copyTemplates.js.map +1 -1
  7. package/bin/regexSimulator.js +233 -0
  8. package/bin/regexSimulator.js.map +1 -0
  9. package/bin/script.js +116 -75
  10. package/bin/script.js.map +1 -1
  11. package/package.json +1 -1
  12. package/src/templates/ts/mysql/default.env +8 -0
  13. package/src/templates/ts/mysql/package.json +38 -0
  14. package/src/templates/ts/mysql/pnpm-lock.yaml +4268 -0
  15. package/src/templates/ts/mysql/src/app.ts +47 -0
  16. package/src/templates/ts/mysql/src/configs/config.ts +13 -0
  17. package/src/templates/ts/mysql/src/configs/db.ts +50 -0
  18. package/src/templates/ts/mysql/src/controllers/auth.controller.ts +92 -0
  19. package/src/templates/ts/mysql/src/controllers/user.controller.ts +66 -0
  20. package/src/templates/ts/mysql/src/dtos/user.dto.ts +13 -0
  21. package/src/templates/ts/mysql/src/interfaces/types.ts +9 -0
  22. package/src/templates/ts/mysql/src/middlewares/auth.middleware.ts +19 -0
  23. package/src/templates/ts/mysql/src/models/user.model.ts +23 -0
  24. package/src/templates/ts/mysql/src/repositories/user.repository.ts +88 -0
  25. package/src/templates/ts/mysql/src/routes/auth.route.ts +9 -0
  26. package/src/templates/ts/mysql/src/routes/user.route.ts +12 -0
  27. package/src/templates/ts/mysql/src/services/user.service.ts +32 -0
  28. package/src/templates/ts/mysql/src/utils/asyncHandler.ts +10 -0
  29. package/src/templates/ts/mysql/src/utils/response.ts +11 -0
  30. package/src/templates/ts/mysql/tsconfig.json +15 -0
@@ -0,0 +1,47 @@
1
+ import express, { Request, Response, NextFunction } from "express";
2
+ import morgan from "morgan";
3
+ import createError from "http-errors";
4
+ import cors from "cors";
5
+ import dotenv from "dotenv";
6
+ import apiRoutes from "./routes/user.route";
7
+ import authRoutes from "./routes/auth.route";
8
+ import { connectDB } from "./configs/db";
9
+ import { ensureUsersTable } from "./models/user.model";
10
+
11
+ dotenv.config();
12
+
13
+ await connectDB();
14
+ await ensureUsersTable();
15
+
16
+ const app = express();
17
+
18
+ // Middlewares
19
+ app.use(cors());
20
+ app.use(express.json());
21
+ app.use(express.urlencoded({ extended: true }));
22
+ app.use(morgan("dev"));
23
+
24
+ // Routes
25
+ app.get("/", (_req: Request, res: Response) =>
26
+ res.json({ message: "API is running 🚀" })
27
+ );
28
+ app.use("/api", apiRoutes);
29
+ app.use("/api/auth", authRoutes);
30
+
31
+ // 404 handler
32
+ app.use((_req: Request, _res: Response, next: NextFunction) => {
33
+ next(createError.NotFound());
34
+ });
35
+
36
+ // Global error handler
37
+ app.use((err: any, _req: Request, res: Response, _next: NextFunction) => {
38
+ res.status(err.status || 500).json({
39
+ success: false,
40
+ message: err.message || "Internal Server Error",
41
+ });
42
+ });
43
+
44
+ const PORT = process.env.PORT || 3000;
45
+ app.listen(PORT, () =>
46
+ console.log(`🚀 Server running @ http://localhost:${PORT}`)
47
+ );
@@ -0,0 +1,13 @@
1
+ import dotenv from "dotenv";
2
+
3
+ dotenv.config();
4
+
5
+ export default {
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 || "test",
11
+ connectionLimit: Number(process.env.DB_CONNECTION_LIMIT) || 10,
12
+ },
13
+ };
@@ -0,0 +1,50 @@
1
+ import mysql, { Pool } from "mysql2/promise";
2
+ import config from "./config";
3
+
4
+ let pool: Pool | null = null;
5
+
6
+ export const connectDB = async (): Promise<void> => {
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
+ const connection = await pool.getConnection();
19
+ try {
20
+ const [rows] = await connection.query("SELECT 1 + 1 AS solution");
21
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
22
+ console.log("The solution is:", (rows as any)[0].solution);
23
+ } finally {
24
+ connection.release();
25
+ }
26
+
27
+ console.log(`✅ MysqlDB Connected: ${config.db.host}`);
28
+ } catch (error: any) {
29
+ console.error("❌ MysqlDB connection error:", error.message);
30
+ process.exit(1);
31
+ }
32
+ };
33
+
34
+ export const getPool = (): Pool => {
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: string, params: any[] = []): Promise<any> => {
42
+ const p = getPool();
43
+ try {
44
+ const [rows] = await p.query(sql, params);
45
+ return rows;
46
+ } catch (error: any) {
47
+ console.error("❌ Query error:", error.message);
48
+ throw error;
49
+ }
50
+ };
@@ -0,0 +1,92 @@
1
+ import asyncHandler from "../utils/asyncHandler";
2
+ import jwt from "jsonwebtoken";
3
+ import bcrypt from "bcryptjs";
4
+ import { successResponse, errorResponse } from "../utils/response";
5
+ import * as userRepo from "../repositories/user.repository";
6
+ import type { Request, Response } from "express";
7
+
8
+ export const login = asyncHandler(async (req: Request, res: Response) => {
9
+ try {
10
+ const { email, password } = req.body as {
11
+ email?: string;
12
+ password?: string;
13
+ };
14
+
15
+ if (!email || !password) {
16
+ return res
17
+ .status(400)
18
+ .json(errorResponse({ status: 400 }, "Email and password required"));
19
+ }
20
+
21
+ const user = await userRepo.getUserByEmail(email);
22
+ if (!user) {
23
+ return res
24
+ .status(401)
25
+ .json(errorResponse({ status: 401 }, "Invalid credentials"));
26
+ }
27
+
28
+ const isMatch = await bcrypt.compare(password, user.password || "");
29
+ if (!isMatch) {
30
+ return res
31
+ .status(401)
32
+ .json(errorResponse({ status: 401 }, "Invalid credentials"));
33
+ }
34
+
35
+ const token = jwt.sign(
36
+ { id: user.id, email: user.email },
37
+ process.env.JWT_SECRET as string,
38
+ { expiresIn: process.env.JWT_EXPIRES_IN || "1d" }
39
+ );
40
+
41
+ res.json(successResponse({ token }, "Login successful"));
42
+ } catch (error) {
43
+ res.status(500).json(errorResponse(error, "Login failed"));
44
+ }
45
+ });
46
+
47
+ export const signup = asyncHandler(async (req: Request, res: Response) => {
48
+ try {
49
+ const { name, email, password, age } = req.body as {
50
+ name?: string;
51
+ email?: string;
52
+ password?: string;
53
+ age?: number;
54
+ };
55
+
56
+ if (!name || !email || !password) {
57
+ return res
58
+ .status(400)
59
+ .json(
60
+ errorResponse({ status: 400 }, "Name, email, and password required")
61
+ );
62
+ }
63
+
64
+ const existingUser = await userRepo.getUserByEmail(email);
65
+ if (existingUser) {
66
+ return res
67
+ .status(400)
68
+ .json(errorResponse({ status: 400 }, "User already exists"));
69
+ }
70
+
71
+ const hashedPassword = await bcrypt.hash(password, 10);
72
+
73
+ const newUser = await userRepo.createUser({
74
+ name,
75
+ email,
76
+ password: hashedPassword,
77
+ age: age || 0,
78
+ });
79
+
80
+ const token = jwt.sign(
81
+ { id: newUser.id, email: newUser.email },
82
+ process.env.JWT_SECRET as string,
83
+ { expiresIn: process.env.JWT_EXPIRES_IN || "1d" }
84
+ );
85
+
86
+ res
87
+ .status(201)
88
+ .json(successResponse({ token, user: newUser }, "Signup successful"));
89
+ } catch (error) {
90
+ res.status(500).json(errorResponse(error, "Signup failed"));
91
+ }
92
+ });
@@ -0,0 +1,66 @@
1
+ import asyncHandler from "../utils/asyncHandler";
2
+ import * as userService from "../services/user.service";
3
+ import { successResponse, errorResponse } from "../utils/response";
4
+ import type { Request, Response } from "express";
5
+
6
+ export const getUsers = asyncHandler(async (_req: Request, res: Response) => {
7
+ try {
8
+ const users = await userService.getAllUsers();
9
+ res.json(successResponse(users));
10
+ } catch (error) {
11
+ res.status(500).json(errorResponse(error, "Failed to fetch users"));
12
+ }
13
+ });
14
+
15
+ export const getUser = asyncHandler(async (req: Request, res: Response) => {
16
+ try {
17
+ const id = Number(req.params.id);
18
+ const user = await userService.getUserById(id);
19
+ if (!user)
20
+ return res
21
+ .status(404)
22
+ .json(errorResponse({ status: 404 }, "User not found"));
23
+ res.json(successResponse(user));
24
+ } catch (error) {
25
+ res.status(500).json(errorResponse(error, "Failed to fetch user"));
26
+ }
27
+ });
28
+
29
+ export const createUser = asyncHandler(async (req: Request, res: Response) => {
30
+ try {
31
+ const data = req.body;
32
+ const user = await userService.createUser(data);
33
+ res.status(201).json(successResponse(user, "User created"));
34
+ } catch (error) {
35
+ res.status(500).json(errorResponse(error, "Failed to create user"));
36
+ }
37
+ });
38
+
39
+ export const updateUser = asyncHandler(async (req: Request, res: Response) => {
40
+ try {
41
+ const id = Number(req.params.id);
42
+ const data = req.body;
43
+ const updated = await userService.updateUser(id, data);
44
+ if (!updated)
45
+ return res
46
+ .status(404)
47
+ .json(errorResponse({ status: 404 }, "User not found"));
48
+ res.json(successResponse(updated, "User updated"));
49
+ } catch (error) {
50
+ res.status(500).json(errorResponse(error, "Failed to update user"));
51
+ }
52
+ });
53
+
54
+ export const deleteUser = asyncHandler(async (req: Request, res: Response) => {
55
+ try {
56
+ const id = Number(req.params.id);
57
+ const deleted = await userService.deleteUser(id);
58
+ if (!deleted)
59
+ return res
60
+ .status(404)
61
+ .json(errorResponse({ status: 404 }, "User not found"));
62
+ res.json(successResponse(deleted, "User deleted"));
63
+ } catch (error) {
64
+ res.status(500).json(errorResponse(error, "Failed to delete user"));
65
+ }
66
+ });
@@ -0,0 +1,13 @@
1
+ export interface CreateUserDTO {
2
+ name: string;
3
+ email: string;
4
+ password: string;
5
+ age?: number;
6
+ }
7
+
8
+ export interface UpdateUserDTO {
9
+ name?: string;
10
+ email?: string;
11
+ password?: string;
12
+ age?: number;
13
+ }
@@ -0,0 +1,9 @@
1
+ export interface User {
2
+ id?: number;
3
+ name: string;
4
+ email: string;
5
+ password?: string;
6
+ age?: number;
7
+ created_at?: string;
8
+ updated_at?: string;
9
+ }
@@ -0,0 +1,19 @@
1
+ import type { Request, Response, NextFunction } from "express";
2
+ import jwt from "jsonwebtoken";
3
+
4
+ export const protect = (req: Request, res: Response, next: NextFunction) => {
5
+ const authHeader = req.headers.authorization;
6
+ if (!authHeader || !authHeader.startsWith("Bearer ")) {
7
+ return res.status(401).json({ success: false, message: "Not authorized" });
8
+ }
9
+
10
+ const token = authHeader.split(" ")[1];
11
+ try {
12
+ const decoded = jwt.verify(token, process.env.JWT_SECRET as string) as any;
13
+ // attach user info to req if needed
14
+ (req as any).user = { id: decoded.id, email: decoded.email };
15
+ next();
16
+ } catch (error) {
17
+ return res.status(401).json({ success: false, message: "Invalid token" });
18
+ }
19
+ };
@@ -0,0 +1,23 @@
1
+ import { query } from "../configs/db";
2
+ import type { User } from "../interfaces/types";
3
+
4
+ export const ensureUsersTable = async (): Promise<void> => {
5
+ const sql = `
6
+ CREATE TABLE IF NOT EXISTS users (
7
+ id INT AUTO_INCREMENT PRIMARY KEY,
8
+ name VARCHAR(255) NOT NULL,
9
+ email VARCHAR(255) NOT NULL UNIQUE,
10
+ password VARCHAR(255) NOT NULL,
11
+ age INT DEFAULT 0,
12
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
13
+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
14
+ ) ENGINE=InnoDB;
15
+ `;
16
+ try {
17
+ await query(sql);
18
+ console.log("✅ Users table ensured");
19
+ } catch (error: any) {
20
+ console.error("❌ Error ensuring users table:", error.message);
21
+ throw error;
22
+ }
23
+ };
@@ -0,0 +1,88 @@
1
+ import { query } from "../configs/db";
2
+ import type { User } from "../interfaces/types";
3
+
4
+ export const getAllUsers = async (): Promise<User[]> => {
5
+ const rows = await query(
6
+ "SELECT id, name, email, age, created_at, updated_at FROM users"
7
+ );
8
+ return rows as User[];
9
+ };
10
+
11
+ export const getUserById = async (id: number): Promise<User | null> => {
12
+ const rows = await query(
13
+ "SELECT id, name, email, age, created_at, updated_at FROM users WHERE id = ?",
14
+ [id]
15
+ );
16
+ return (rows[0] as User) || null;
17
+ };
18
+
19
+ export const getUserByEmail = async (email: string): Promise<User | null> => {
20
+ const rows = await query(
21
+ "SELECT id, name, email, password, age, created_at, updated_at FROM users WHERE email = ?",
22
+ [email]
23
+ );
24
+ return (rows[0] as User) || null;
25
+ };
26
+
27
+ export const createUser = async (data: Partial<User>): Promise<User> => {
28
+ const { name, email, password, age = 0 } = data as User;
29
+ const insertResult: any = await query(
30
+ "INSERT INTO users (name, email, password, age, created_at, updated_at) VALUES (?, ?, ?, ?, NOW(), NOW())",
31
+ [name, email, password, age]
32
+ );
33
+
34
+ if (!insertResult || !insertResult.insertId) {
35
+ throw new Error("Failed to create user - no insert ID returned");
36
+ }
37
+
38
+ return (await getUserById(insertResult.insertId)) as User;
39
+ };
40
+
41
+ export const updateUser = async (
42
+ id: number,
43
+ data: Partial<User>
44
+ ): Promise<User | null> => {
45
+ const fields: string[] = [];
46
+ const params: any[] = [];
47
+
48
+ if (data.name !== undefined) {
49
+ fields.push("name = ?");
50
+ params.push(data.name);
51
+ }
52
+ if (data.email !== undefined) {
53
+ fields.push("email = ?");
54
+ params.push(data.email);
55
+ }
56
+ if (data.password !== undefined) {
57
+ fields.push("password = ?");
58
+ params.push(data.password);
59
+ }
60
+ if (data.age !== undefined) {
61
+ fields.push("age = ?");
62
+ params.push(data.age);
63
+ }
64
+
65
+ if (fields.length === 0) {
66
+ return await getUserById(id);
67
+ }
68
+
69
+ params.push(id);
70
+ const updateResult: any = await query(
71
+ `UPDATE users SET ${fields.join(", ")}, updated_at = NOW() WHERE id = ?`,
72
+ params
73
+ );
74
+
75
+ if (!updateResult || updateResult.affectedRows === 0) {
76
+ return null;
77
+ }
78
+
79
+ return await getUserById(id);
80
+ };
81
+
82
+ export const deleteUser = async (id: number): Promise<User | null> => {
83
+ const user = await getUserById(id);
84
+ if (!user) return null;
85
+
86
+ await query("DELETE FROM users WHERE id = ?", [id]);
87
+ return user;
88
+ };
@@ -0,0 +1,9 @@
1
+ import { Router } from "express";
2
+ import * as authController from "../controllers/auth.controller";
3
+
4
+ const router = Router();
5
+
6
+ router.post("/login", authController.login);
7
+ router.post("/signup", authController.signup);
8
+
9
+ export default router;
@@ -0,0 +1,12 @@
1
+ import { Router } from "express";
2
+ import * as userController from "../controllers/user.controller";
3
+
4
+ const router = Router();
5
+
6
+ router.get("/users", userController.getUsers);
7
+ router.get("/users/:id", userController.getUser);
8
+ router.post("/users", userController.createUser);
9
+ router.put("/users/:id", userController.updateUser);
10
+ router.delete("/users/:id", userController.deleteUser);
11
+
12
+ export default router;
@@ -0,0 +1,32 @@
1
+ import * as userRepo from "../repositories/user.repository";
2
+ import type { User } from "../interfaces/types";
3
+ import { CreateUserDTO, UpdateUserDTO } from "../dtos/user.dto";
4
+
5
+ export const getAllUsers = async (): Promise<User[]> => {
6
+ return await userRepo.getAllUsers();
7
+ };
8
+
9
+ export const getUserById = async (id: number): Promise<User | null> => {
10
+ return await userRepo.getUserById(id);
11
+ };
12
+
13
+ export const getUserByEmail = async (email: string): Promise<User | null> => {
14
+ return await userRepo.getUserByEmail(email);
15
+ };
16
+
17
+ export const createUser = async (
18
+ data: Partial<CreateUserDTO>
19
+ ): Promise<User> => {
20
+ return await userRepo.createUser(data);
21
+ };
22
+
23
+ export const updateUser = async (
24
+ id: number,
25
+ data: Partial<UpdateUserDTO>
26
+ ): Promise<User | null> => {
27
+ return await userRepo.updateUser(id, data);
28
+ };
29
+
30
+ export const deleteUser = async (id: number): Promise<User | null> => {
31
+ return await userRepo.deleteUser(id);
32
+ };
@@ -0,0 +1,10 @@
1
+ import type { Request, Response, NextFunction } from "express";
2
+
3
+ export default function asyncHandler(
4
+ fn: (req: Request, res: Response, next: NextFunction) => Promise<any>
5
+ ) {
6
+ return function (req: Request, res: Response, next: NextFunction) {
7
+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
8
+ fn(req, res, next).catch(next);
9
+ };
10
+ }
@@ -0,0 +1,11 @@
1
+ export const successResponse = (data: any = {}, message = "Success") => ({
2
+ success: true,
3
+ message,
4
+ data,
5
+ });
6
+
7
+ export const errorResponse = (error: any = {}, message = "Error") => ({
8
+ success: false,
9
+ message,
10
+ error,
11
+ });
@@ -0,0 +1,15 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "module": "ESNext",
5
+ "moduleResolution": "node",
6
+ "outDir": "dist",
7
+ "rootDir": "src",
8
+ "esModuleInterop": true,
9
+ "forceConsistentCasingInFileNames": true,
10
+ "strict": true,
11
+ "skipLibCheck": true,
12
+ "resolveJsonModule": true
13
+ },
14
+ "include": ["src/**/*"]
15
+ }