@tmraaex/create-structure
Version:
CLI-verktyg för att skapa en standardiserad projektstruktur med TypeScript
233 lines (195 loc) • 6.95 kB
JavaScript
import fs from "fs";
import path from "path";
const createTodoService = (root, databaseChoice) => {
// Do nothing if the database choice is "custom"
if (databaseChoice === "custom") return;
console.log(path.join(root, "src/services"));
fs.mkdirSync(path.join(root, "src", "services"), { recursive: true });
// Define paths where the model and service files will be saved
const modelPath = path.join(root, "src/models/todoModel.ts");
const servicePath = path.join(root, "src/services/todoService.ts");
// Create the MySQL Todo model and service
if (databaseChoice === "mysql (orm)") {
const mysqlModel = `
import { Sequelize, DataTypes, Model } from "sequelize";
import { db } from @config/database"; // Import database connection
class Todo extends Model {
public id!: number;
public task!: string;
public completed!: boolean;
}
Todo.init(
{
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true,
allowNull: false,
},
task: {
type: DataTypes.STRING,
allowNull: false,
},
completed: {
type: DataTypes.BOOLEAN,
defaultValue: false,
},
},
{
sequelize: db, // Use the database connection from the config
modelName: "Todo", // Name of the model
tableName: "todos", // Name of the table
timestamps: true, // Include createdAt, updatedAt
}
);
export default Todo;
`;
const mysqlService = `
import Todo from "@models/todoModel"; // Import the Todo model
import { db } from "@config/database";
import {ITodo} from "@interfaces/ITodo"
// Service to get all todos from MySQL database
const getAllTodos = async () => {
try {
// Sync the database - Create table if it doesn't exist
await db.sync(); // This will create the table if it doesn't exist
const todos = await Todo.findAll();
return todos; // Return all Todo instances
} catch (error) {
console.error("[TodoService]: Error fetching todos", error);
throw new Error("[TodoService]: Unable to fetch todos.");
}
};
// Service to create a new todo in MySQL
const createTodo = async (task: Todo["task"], completed = false) => {
try {
const newTodo = await Todo.create({ task, completed });
return newTodo; // Return the newly created Todo instance
} catch (error) {
console.error("[TodoService]: Error creating todo", error);
throw new Error("[TodoService]: Unable to create todo.");
}
};
export { getAllTodos, createTodo };
`;
// Write MySQL model and service to files
fs.writeFileSync(modelPath, mysqlModel, "utf8");
fs.writeFileSync(servicePath, mysqlService, "utf8");
console.log("✅ MySQL model and service created.");
}
// Create the MongoDB Todo model and service
if (databaseChoice === "mongodb") {
const mongodbModel = `
import mongoose from "mongoose";
const todoSchema = new mongoose.Schema({
task: { type: String, required: true },
completed: { type: Boolean, default: false },
}, {timestamps: true});
const Todo = mongoose.model("Todo", todoSchema);
export default Todo;
`;
const mongodbService = `
import Todo from "@models/todoModel"; // Import the MongoDB Todo model
import {ITodo} from "@interfaces/ITodo"
// Service to get all todos from MongoDB database
const getAllTodos = async () => {
try {
const todos = await Todo.find();
return todos; // Return all Todo instances
} catch (error) {
console.error("[TodoService]: Error fetching todos", error);
throw new Error("[TodoService]: Unable to fetch todos.");
}
};
// Service to create a new todo in MongoDB
const createTodo = async (task: ITodo["task"], completed = false) => {
try {
const newTodo = new Todo({
task,
completed
});
await newTodo.save(); // Save the new Todo to MongoDB
return newTodo; // Return the newly created Todo instance
} catch (error) {
console.error("[TodoService]: Error creating todo", error);
throw new Error("[TodoService]: Unable to create todo.");
}
};
export { getAllTodos, createTodo };
`;
// Write MongoDB model and service to files
fs.writeFileSync(modelPath, mongodbModel, "utf8");
fs.writeFileSync(servicePath, mongodbService, "utf8");
console.log("✅ MongoDB model and service created.");
}
if (databaseChoice === "mysql (raw)") {
const mysqlRAWService = `
import { db } from "@config/database";
import ITodo from "@interfaces/ITodo";
import { ResultSetHeader } from "mysql2";
export const getAllTodos = async () => {
try {
const connection = await db.getConnection();
const query = \`SELECT * FROM todos\`;
const [rows] = await connection.query(query);
if(connection) connection.release();
return rows;
} catch (err) {
console.error(err);
throw new Error(err instanceof Error ? err.message : "Unknown Error");
}
};
export const createTodo = async (
task: ITodo["task"],
completed: Todo["completed"] = false
) => {
try {
const connection = await db.getConnection();
const query = \`INSERT INTO todos (task, completed, createdAt, updatedAt) VALUES (?,?,?,?)\`;
const values = [task, completed, new Date(), new Date()];
const [result] = await connection.query<ResultSetHeader>(query, values);
if(connection) connection.release();
return { id: result.insertId, task, completed };
} catch (err) {
console.error(err);
throw new Error(err instanceof Error ? err.message : "Unknown Error");
}
};
export const updateTodo = async (todo: ITodo)=>{
const {
task,
completed
} = todo
try{
const connection = await db.getConnection();
const query = \`UPDATE todos SET (task, completed,updatedAt) VALUES = (?,?,?)\`
values = [task, completed, new Date()]
const [result] = await connection.query<ResultSetHeader>(query, values)
if(connection) connection.release();
return result;
}catch (err) {
console.error(err);
throw new Error(err instanceof Error ? err.message : "Unknown Error");
}
};
export const deleteTodo = async (id: ITodo["id"]) =>{
try {
const connection = await db.getConnection();
const query = \`DELETE FROM todos WHERE id = ? LIMIT 1\`;
const values = [id]
const [result] = connection.query<ResultSetHeader>(query, values)
return result;
}catch (err) {
console.error(err);
throw new Error(err instanceof Error ? err.message : "Unknown Error");
}finally{
if(connection) connection.release();
}
};
`;
// Write MySQL model and service to files
fs.writeFileSync(servicePath, mysqlRAWService, "utf8");
console.log("✅ MySQL model and service created.");
}
};
export { createTodoService };