Skip to content

Commit

Permalink
feat: Added generate functionality and update deps [2.6.1]
Browse files Browse the repository at this point in the history
  • Loading branch information
Abhishek-Mallick committed Sep 26, 2024
1 parent e1f57b5 commit 82a87b1
Show file tree
Hide file tree
Showing 9 changed files with 361 additions and 12 deletions.
1 change: 1 addition & 0 deletions .npmignore
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ template/
.github/
.vscode/
.releaserc.json
LICENSE

# for 2.4.5 release
bin/format/
8 changes: 5 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
<a href="https://www.npmjs.com/package/universal-box">
<img src="https://github.com/user-attachments/assets/6a8119d2-e60a-470e-b426-a598df1aa862" width="140px" alt="Universal Box Logo">
</a>
<h1>Universal-Box</h1>
<br>
<br/>

Expand All @@ -12,6 +13,7 @@
<a href="https://www.npmjs.com/package/universal-box" target="_blank"><img src="https://img.shields.io/npm/v/universal-box?style=flat&colorA=000000&colorB=000000" alt="NPM Version" /></a>
<a href="https://www.npmjs.com/package/universal-box" target="_blank"><img src="https://img.shields.io/npm/dt/universal-box?style=flat&colorA=000000&colorB=000000" alt="NPM Downloads" /></a>
<a href="https://discord.gg/NBR9JmWys4" target="_blank"><img src="https://img.shields.io/discord/1164935524990066740?style=flat&colorA=000000&colorB=000000&label=discord&logo=discord&logoColor=ffffff" /></a>
<a href="https://opensource.org/licenses/Apache-2.0"><img alt="License" src="https://img.shields.io/github/license/Abhishek-Mallick/universal-box?color=black" /></a>
<a href="https://snyk.io/advisor/npm-package/universal-box" target="_blank">
<img src="https://snyk.io/advisor/npm-package/universal-box/badge.svg" alt="Snyk" style="border: none;"/>
</a>
Expand All @@ -20,7 +22,7 @@
<tbody>
<tr>
<td>
<a href="https://universal-box.co/">📚 Read the docs</a>
<a href="https://universal-box.dev/">📚 Read the docs</a>
</td>
<td>
<a href="https://discord.gg/NBR9JmWys4">💬 Join our Discord</a>
Expand All @@ -33,7 +35,7 @@
</table>
</div>

# Universal-Box


**Universal-Box** is a powerful tool designed to streamline your development process with a collection of starter templates and projects. It provides a fast and structured way to kickstart your development journey, allowing you to set up new projects with ease and efficiency.

Expand Down Expand Up @@ -77,7 +79,7 @@ universal-box get https://github.com/username/repo/tree/<path_to_sub-directory>

## Documentation

For more details and advanced usage, visit the [Universal-Box Documentation](https://universal-box.co/).
For more details and advanced usage, visit the [Universal-Box Documentation](https://universal-box.dev/).

## License

Expand Down
50 changes: 50 additions & 0 deletions bin/generate/codePopulate.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
module.exports = {
modelsContent: function (item) {
return `
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const ${item}Schema = new Schema({}); // Write your schema here
const ${item} = mongoose.model('${item}', ${item}Schema);
module.exports = ${item};
`;
},

viewsContent: function (item) {
return `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>${item}</title>
</head>
<body>
</body>
</html>
`;
},

controllerContent: function (functions_array) {
return `module.exports = {\n${functions_array
.map((item) => `${item}: function() {}, // Add function logic here`)
.join("\n")}\n};`;
},

routesContent: function (config) {
let base_content = `const router = require('express').Router();\n\n`;

Object.entries(config).forEach(([type, routes]) => {
routes.forEach((route) => {
base_content += `router.${type}('${route}', (req, res) => {}); // Add your route logic here\n`;
});
});

base_content += `\nmodule.exports = router;`;
return base_content;
},
};
97 changes: 97 additions & 0 deletions bin/generate/fileGenerators.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
const fs = require("fs");
const util = require("util");

const fsWritePromisified = util.promisify(fs.writeFile);

const errorHandler = (err) => console.log("\x1b[31m", err);
const successHandler = (fileName) => () =>
console.log("\x1b[32m", `Generated file ${fileName}`);

module.exports = {
makeModels: function (models) {
return models.map((item) =>
fsWritePromisified(
`./models/${item}.js`,
`
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const ${item}Schema = new Schema({}); // Write your schema here
const ${item} = mongoose.model('${item}', ${item}Schema);
module.exports = ${item};
`
)
.then(successHandler(`${item}.js`))
.catch(errorHandler)
);
},

makeViews: function (views) {
return views.map((item) =>
fsWritePromisified(
`./views/${item}.html`,
`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>${item}</title>
</head>
<body>
</body>
</html>
`
)
.then(successHandler(`${item}.html`))
.catch(errorHandler)
);
},

makeControllers: function (controllers) {
return Object.entries(controllers).map(([fileName, methods]) =>
fsWritePromisified(
`./controllers/${fileName}.js`,
`
module.exports = {
${methods
.map((method) => `${method}: function() {}, // Add function logic here`)
.join("\n")}
};
`
)
.then(successHandler(`${fileName}.js`))
.catch(errorHandler)
);
},

makeRoutes: function (routes) {
return Object.entries(routes).map(([fileName, methods]) =>
fsWritePromisified(
`./routes/${fileName}.js`,
`
const router = require('express').Router();
${Object.entries(methods)
.map(([methodType, paths]) =>
paths
.map(
(path) =>
`router.${methodType}('${path}', (req, res) => {}); // Add your route logic here`
)
.join("\n")
)
.join("\n")}
module.exports = router;
`
)
.then(successHandler(`${fileName}.js`))
.catch(errorHandler)
);
},
};
152 changes: 152 additions & 0 deletions bin/generate/generate-from-config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
const fs = require("fs");
const yaml = require("js-yaml");
const utils = require("./utils");
const chalk = require("chalk");

function generateFromConfig(configFileName) {
const configPath = `${process.cwd()}/${configFileName}`;

// Check if the config file exists
if (!fs.existsSync(configPath)) {
console.error(`Configuration file "${configFileName}" not found.`);
process.exit(1);
}

let config;
try {
const fileContents = fs.readFileSync(configPath, "utf8");
config = yaml.load(fileContents);
} catch (e) {
console.error(`Error reading or parsing "${configFileName}": ${e.message}`);
process.exit(1);
}

createProjectStructure(config);

console.log(
chalk.blue("\n------ Happy Coding with Universal-Box 🚀 ------\n")
);
}

function createProjectStructure(config) {
const { models, controllers, views, routes } = config;
console.log(chalk.blue("Creating project structure..."));
if (models) {
utils
.makeFolders(["models"])
.then(() => {
return Promise.all(
models.map((model) => {
return fs.promises.writeFile(
`models/${model}.js`,
`
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const ${model}Schema = new Schema({}); // Write your schema here
const ${model} = mongoose.model('${model}', ${model}Schema);
module.exports = ${model};
`
);
})
);
})
.then(() =>
console.log(chalk.yellow("\x1b[32m", "✅ Models generated"))
)
.catch((err) => console.error(err));
}

if (views) {
utils
.makeFolders(["views"])
.then(() => {
return Promise.all(
views.map((view) => {
return fs.promises.writeFile(
`views/${view}.html`,
`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>${view}</title>
</head>
<body>
</body>
</html>
`
);
})
);
})
.then(() =>
console.log(chalk.yellow("\x1b[32m", "✅ Views generated"))
)
.catch((err) => console.error(err));
}

if (controllers) {
utils
.makeFolders(["controllers"])
.then(() => {
return Promise.all(
Object.entries(controllers).map(([fileName, methods]) => {
const content = `
module.exports = {
${methods
.map((method) => `${method}: function() {}, // Add function logic here`)
.join("\n")}
};
`;
return fs.promises.writeFile(`controllers/${fileName}.js`, content);
})
);
})
.then(() =>
console.log(
chalk.yellow("\x1b[32m", "✅ Controllers generated")
)
)
.catch((err) => console.error(err));
}

if (routes) {
utils
.makeFolders(["routes"])
.then(() => {
return Promise.all(
Object.entries(routes).map(([fileName, methods]) => {
const content = `
const router = require('express').Router();
${Object.entries(methods)
.map(([methodType, paths]) =>
paths
.map(
(path) =>
`router.${methodType}('${path}', (req, res) => {}); // Add your route logic here`
)
.join("\n")
)
.join("\n")}
module.exports = router;
`;
return fs.promises.writeFile(`routes/${fileName}.js`, content);
})
);
})
.then(() =>
console.log(chalk.yellow("\x1b[32m", "✅ Routes generated"))
)
.catch((err) => console.error(err));
}
}

module.exports = { generateFromConfig };
28 changes: 28 additions & 0 deletions bin/generate/utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
const fs = require("fs");
var exec = require("child_process").exec;
const chalk = require("chalk");

module.exports = {
makeFolders: function (array_list) {
const supportedFolders = ["models", "views", "controllers", "routes"];

return new Promise((resolve, reject) => {
array_list.forEach((folder) => {
if (supportedFolders.includes(folder)) {
if (!fs.existsSync(`./${folder}`)) {
fs.mkdirSync(`./${folder}`);
console.log(chalk.yellow(`Directory Created -> ./${folder}`));
}
} else {
console.log("\x1b[31m", `NO SUPPORT FOR DIRECTORY ./${folder}`);
reject({
success: false,
message: "No support for entered directory!",
});
}
});

resolve({ success: true, message: "Created folders successfully" });
});
},
};
Loading

0 comments on commit 82a87b1

Please sign in to comment.