crud-app-generator
Version:
A simple CRUD API generator in Node.js, Express.js and MongoDB
107 lines (94 loc) • 2.68 kB
JavaScript
/**
* Project: Project Starter
* Description: Script to create a basic project structure
* Author: Coder Nexus
* License: MIT
*/
;
const fs = require("fs");
const path = require("path");
// Import content templates
const {
appContent,
envContent,
gitignoreContent,
packageContent,
controllerContent,
modelContent,
routeContent,
apiTestContent,
controllerTestContent,
indexHtmlContent,
} = require("../content");
/**
* Function to create the project structure
* @param {Object} options - Project options (projectName, mongoUrl, collection, port)
*/
const createProjectStructure = ({
projectName,
mongoUrl,
collection,
schema,
port,
}) => {
// Define project path
const projectPath = path.join("./", projectName);
// Check if project directory already exists
if (!fs.existsSync(projectPath)) {
// Create project directory
fs.mkdirSync(projectPath);
// Create subdirectories
const subdirectories = [
"controllers",
"models",
"routes",
"public",
"tests",
];
subdirectories.forEach((dir) => {
fs.mkdirSync(path.join(projectPath, dir));
});
// Create source files
const sourceFiles = {
"app.js": appContent({ collection }),
".env": envContent({ mongoUrl, port }),
".gitignore": gitignoreContent(),
"package.json": packageContent({ projectName }),
"public/index.html": indexHtmlContent({ collection }),
["controllers/" + collection + "Controller.js"]: controllerContent({
collection,
}),
["models/" + collection + "Model.js"]: modelContent({
collection,
schema,
}),
["routes/" + collection + "Route.js"]: routeContent({ collection }),
["tests/" + collection + "Api.test.js"]: apiTestContent({ collection }),
["tests/" + collection + "Controller.test.js"]: controllerTestContent({
collection,
}),
};
// Write source files to disk
Object.entries(sourceFiles).forEach(([file, content]) => {
const filePath = path.join(projectPath, file);
if (!fs.existsSync(filePath)) {
fs.writeFileSync(filePath, content);
}
fs.writeFileSync(filePath, content);
});
// Print success message and instructions
console.log(`Project created with name: ${projectName}, Next step:
cd ${projectName}
npm install
To run the project:
npm run dev
To run unit test:
npm run test
`);
} else {
// Print error message if project directory already exists
console.error(`Directory/Project already exists with name ${projectName}`);
}
};
module.exports = { createProjectStructure };