@tmraaex/create-structure
Version:
CLI-verktyg fΓΆr att skapa en standardiserad projektstruktur med TypeScript
191 lines (159 loc) β’ 6.19 kB
JavaScript
import fs from "fs-extra";
import path from "path";
import { fileURLToPath } from "url";
import { execSync } from "child_process";
import { createTodoService } from "./createTodoService.js";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const createExpressStructure = (root, databaseChoice) => {
const templatePath = path.join(__dirname, "./express-typescript"); // Source template directory
try {
// Copy the general express template
fs.copySync(templatePath, root, { overwrite: true });
console.log("β
Express struktur skapad.");
// Only handle database configuration if Express is selected
if (databaseChoice === "mongodb") {
createMongoDBConfig(root);
//creates service and model for todos based on database choice
createTodoService(root, databaseChoice);
} else if (databaseChoice === "mysql (orm)") {
createMySQLConfig(root);
//creates service and model for todos based on database choice
createTodoService(root, databaseChoice);
} else if (databaseChoice === "mysql (raw)") {
createMySQLRAWConfig(root);
//creates service and model for todos based on database choice
createTodoService(root, databaseChoice);
} else if (databaseChoice === "custom") {
console.log("π§ Skipping database configuration (Custom selected).");
fs.remove(path.join(root, "src/controllers/todoController.ts"));
}
const readmePath = path.join(root, "README.md");
let openReadme;
if (process.platform === "darwin") {
openReadme = `open ${readmePath}`; // macOS
} else if (process.platform === "win32") {
openReadme = `start ${readmePath}`; // Windows
} else if (process.platform === "linux") {
openReadme = `xdg-open ${readmePath}`; // Linux
}
execSync(openReadme, { stdio: "inherit" });
} catch (error) {
console.error("β Error creating Express structure:", error);
}
};
const createMongoDBConfig = (root) => {
const dbConfig = `
import mongoose from "mongoose";
import dotenv from "dotenv";
dotenv.config();
// MongoDB connection URI from environment variables or fallback to default
const MONGO_URI = process.env.MONGO_URI || "mongodb://localhost:27017/mydb";
// Function to connect to MongoDB
const connectToDb = async (): Promise<void> => {
try {
await mongoose.connect(MONGO_URI);
console.log("[Database]: β
Connected to MongoDB");
} catch (err) {
console.error("[Database]: β MongoDB Connection Error:", err);
throw new Error("[Database]: Failed to connect to MongoDB");
}
};
// Export mongoose (db) and the connectToDb function
export { mongoose as db, connectToDb };
`;
fs.writeFileSync(path.join(root, "src/config/database.ts"), dbConfig, "utf8");
console.log("β
MongoDB config skapad.");
// Install MongoDB dependencies (mongoose and dotenv)
try {
console.log("π Installing MongoDB dependencies...");
execSync(`cd ${root} && npm install mongoose dotenv`, { stdio: "inherit" });
console.log("β
MongoDB dependencies installed.");
} catch (error) {
console.error("β Error installing MongoDB dependencies:", error.message);
}
};
const createMySQLConfig = (root) => {
const dbConfig = `
import { Sequelize } from "sequelize";
import dotenv from "dotenv";
dotenv.config();
const MYSQL_DB = process.env.MYSQL_DB || "mydb";
const MYSQL_USER = process.env.MYSQL_USER || "root";
const MYSQL_PASSWORD = process.env.MYSQL_PASSWORD || "";
const MYSQL_HOST = process.env.MYSQL_HOST || "localhost";
const sequelize = new Sequelize(MYSQL_DB, MYSQL_USER, MYSQL_PASSWORD, {
host: MYSQL_HOST,
dialect: "mysql",
logging: false,
});
export const connectToDb = async (): Promise<void> => {
try {
await sequelize.authenticate();
console.log("[Database]: β
Connected to MySQL");
} catch (err) {
console.error("[Database]: β MySQL Connection Error:", err);
throw new Error("[Database]: Connection to MySQL failed");
}
};
export {sequelize as db};
`;
fs.writeFileSync(path.join(root, "src/config/database.ts"), dbConfig, "utf8");
console.log("β
MySQL config skapad.");
// Install MySQL dependencies (sequelize, mysql2, and dotenv)
try {
console.log("π Installing MySQL dependencies...");
execSync(`cd ${root} && npm install sequelize mysql2`, {
stdio: "inherit",
});
console.log("β
MySQL dependencies installed.");
} catch (error) {
console.error("β Error installing MySQL dependencies:", error.message);
}
};
const createMySQLRAWConfig = (root) => {
const dbConfig = `
import mysql from "mysql2/promise";
import dotenv from "dotenv";
dotenv.config();
const MYSQL_DB = process.env.MYSQL_DB || "mydb";
const MYSQL_USER = process.env.MYSQL_USER || "root";
const MYSQL_PASSWORD = process.env.MYSQL_PASSWORD || "";
const MYSQL_HOST = process.env.MYSQL_HOST || "localhost";
export const db = mysql.createPool({
host: MYSQL_HOST,
user: MYSQL_USER,
database: MYSQL_DB,
password: MYSQL_PASSWORD,
waitForConnections: true,
connectionLimit: 10,
maxIdle: 10,
idleTimeout: 60000,
queueLimit: 0,
enableKeepAlive: true,
keepAliveInitialDelay: 0,
});
//test connection
export const connectToDb = async () => {
try {
const conn = await db.getConnection();
console.log("[Database]: β
Connected to MySQL");
conn.release();
} catch (err) {
console.error("[Database]: β MySQL Connection Error:", err);
throw new Error("[Database]: Connection to MySQL failed");
}
};
`;
fs.writeFileSync(path.join(root, "src/config/database.ts"), dbConfig, "utf8");
console.log("β
MySQL config skapad.");
try {
console.log("π Installing MySQL dependencies...");
execSync(`cd ${root} && npm install mysql2`, {
stdio: "inherit",
});
console.log("β
MySQL dependencies installed.");
} catch (error) {
console.error("β Error installing MySQL dependencies:", error.message);
}
};
export { createExpressStructure };