{"id":17601149,"url":"https://github.com/pranavbarthwal/backend-generator-cli","last_synced_at":"2025-04-09T21:18:32.437Z","repository":{"id":254841662,"uuid":"847708229","full_name":"PranavBarthwal/backend-generator-cli","owner":"PranavBarthwal","description":"Backend Generator CLI is a simple yet powerful command-line tool that helps you quickly scaffold a well-structured backend project. With built-in best practices and customizable code snippets, this tool is designed to streamline your development workflow and help you focus on what matters: building your application. Link to the npm package👇","archived":false,"fork":false,"pushed_at":"2025-03-15T03:44:34.000Z","size":235,"stargazers_count":45,"open_issues_count":26,"forks_count":19,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-04-09T21:18:28.433Z","etag":null,"topics":["backend","express","gssoc-ext","hacktoberfest","hacktoberfest-accepted","javascript","mern-stack","nodejs","npm","npm-cli","npm-package","npm-packages","npmjs","react"],"latest_commit_sha":null,"homepage":"https://backend-gen-cli.pranavbarthwal.tech/","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/PranavBarthwal.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-08-26T11:51:23.000Z","updated_at":"2025-03-29T17:25:51.000Z","dependencies_parsed_at":null,"dependency_job_id":"619ba07b-2c1d-4ba7-b14f-26b27a3417b8","html_url":"https://github.com/PranavBarthwal/backend-generator-cli","commit_stats":{"total_commits":61,"total_committers":13,"mean_commits":"4.6923076923076925","dds":0.6557377049180328,"last_synced_commit":"b21a93eb38172bbbe80fd062fba11b9c6f695966"},"previous_names":["pranavbarthwal/backend-generator-cli"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PranavBarthwal%2Fbackend-generator-cli","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PranavBarthwal%2Fbackend-generator-cli/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PranavBarthwal%2Fbackend-generator-cli/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PranavBarthwal%2Fbackend-generator-cli/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/PranavBarthwal","download_url":"https://codeload.github.com/PranavBarthwal/backend-generator-cli/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248111973,"owners_count":21049578,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["backend","express","gssoc-ext","hacktoberfest","hacktoberfest-accepted","javascript","mern-stack","nodejs","npm","npm-cli","npm-package","npm-packages","npmjs","react"],"created_at":"2024-10-22T12:08:46.149Z","updated_at":"2025-04-09T21:18:32.409Z","avatar_url":"https://github.com/PranavBarthwal.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003cimg src=\"https://github.com/user-attachments/assets/1226438f-19e0-46e4-beff-5483e429ee69\" width=200\u003e\n\n\u003cdiv id=\"top\"\u003e\u003c/div\u003e\n\n# Backend Generator CLI\n\n\u003e **Now supporting AI powered code snippet generation!** 🚀\n\n![npm](https://img.shields.io/npm/dt/backend-generator-cli?color=brightgreen\u0026label=Total%20Downloads\u0026style=for-the-badge) ![npm](https://img.shields.io/npm/dw/backend-generator-cli?color=blue\u0026label=Weekly%20Downloads\u0026style=for-the-badge)\n\n**Backend Generator CLI** is a simple yet powerful command-line tool that helps you quickly scaffold a well-structured backend project. With built-in best practices and customizable code snippets, this tool is designed to streamline your development workflow and help you focus on what matters: building your application.\n\n## GitHub Repository Stats\n| 🌟 **Stars** | 🍴 **Forks** | 🐛 **Issues** | 🔔 **Open PRs** | 🔕 **Closed PRs** | 🛠️ **Languages** | ✅ **Contributors** |\n|--------------|--------------|---------------|-----------------|------------------|------------------|------------------|\n| ![GitHub stars](https://img.shields.io/github/stars/PranavBarthwal/backend-generator-cli) | ![forks](https://img.shields.io/github/forks/PranavBarthwal/backend-generator-cli) | ![issues](https://img.shields.io/github/issues/PranavBarthwal/backend-generator-cli?color=32CD32) | ![pull requests](https://img.shields.io/github/issues-pr/PranavBarthwal/backend-generator-cli?color=FFFF8F) | ![Closed PRs](https://img.shields.io/github/issues-pr-closed/PranavBarthwal/backend-generator-cli?color=20B2AA) | ![Languages](https://img.shields.io/github/languages/count/PranavBarthwal/backend-generator-cli?color=20B2AA) | ![Contributors](https://img.shields.io/github/contributors/PranavBarthwal/backend-generator-cli?color=00FA9A) |\n\n## Key Features\n\n-   **Instant Backend Setup**: Generate a clean, well-organized backend project structure with a single command.\n-   **Best Practices Built-in**: The generated project follows industry-standard best practices for scalable backend development.\n-   **Custom Code Snippets**: Insert predefined code snippets such as API error handling, file uploading, and more using simple CLI commands.\n-   **AI-powered Custom Code Snippets**: Generate customizable code snippets using Generative AI with simple CLI commands.\n-   **Modular and Extensible**: The tool allows you to customize and expand the project structure to meet your specific needs.\n\n## Index\n\n-   [Installation](#installation)\n-   [Commands](#commands)\n    -   [1. run create-project](#1-run-create-project)\n    -   [2. run generate-snippet](#2-run-generate-snippet-snippet-name)\n    -   [3. run generate-ai-snippet](#3-run-generate-ai-snippet-snippetname)\n-   [Full User Journey Example](#full-user-journey-example)\n-   [Future Enhancements](#future-enhancements)\n-   [License](#license)\n\n---\n\n## Installation\n\nTo install the CLI globally, use `npm`:\n\n```bash\nnpm install -g backend-generator-cli\n```\n\nAfter installation, you will have access to two main commands: `create-project` to generate the backend structure and `generate-snippet` to inject code snippets.\n\n## Commands\n\n### 1. `run create-project`\n\nGenerate a new backend project with a pre-configured folder structure:\n\n```bash\nrun create-project\n```\n\nThis command will create a new backend project structure in your current directory. Here's what the generated structure looks like:\n\n```\n.\n├── src/\n│   ├── controllers/      # Controllers for handling requests and responses\n│   ├── db/               # Database connection and configuration\n│   ├── middlewares/      # Middlewares for handling validation and request processing\n│   ├── models/           # Data models (e.g., Mongoose models, SQL models)\n│   ├── routes/           # API route definitions\n│   ├── utils/            # Utility functions and helpers\n│   ├── app.js            # Main app setup and configuration\n│   ├── constants.js      # Application-wide constants\n│   └── index.js          # Entry point of the backend server\n├── .env.sample           # Sample environment configuration\n├── .gitignore            # Git ignore file for version control\n├── .prettierignore       # Prettier ignore file\n├── .prettierrc           # Prettier configuration\n├── package.json          # Project dependencies and scripts\n└── README.md             # Documentation\n```\n\nThis structure is clean, easy to navigate, and ready to be extended with your own business logic and data models.\n\n### 2. `run generate-snippet \u003csnippet-name\u003e`\n\nGenerate and inject predefined code snippets into your project. Snippets are placed in individual files in your current working directory.\n\nExample:\n\n```bash\nrun generate-snippet multer-file-upload\n```\n\nThis command will create a new file `multer-file-upload.js` in the current working directory, containing a pre-configured snippet for handling file uploads using `multer`.\n\n### Available Snippets\n1. **`express-server`**:\n   Sets up express server.\n   \n   **Code Snippet**:\n   ```js\n   import express from \"express\";\n   const app = express();\n   const PORT = process.env.PORT || 3000;\n   app.listen(PORT, () =\u003e console.log(`Server started at ${PORT}`));\n   ```\n\n2. **`async-ops-handler`**:\n   Handles asynchronous operations with error handling.\n\n    **Code Snippet**:\n    ```js\n    const asyncHandler = (requestHandler) =\u003e {\n    \treturn (req, res, next) =\u003e {\n    \t\tPromise.resolve(requestHandler(req, res, next)).catch((err) =\u003e next(err));\n    \t};\n    };\n    export { asyncHandler };\n    ```\n\n3. **`custom-api-error`**:\n    Standardizes error responses for your API.\n\n    **Code Snippet**:\n    ```js\n    class ApiError extends Error {\n    \tconstructor(statusCode, message = 'Something went wrong', errors = [], stack = '') {\n    \t\tsuper(message);\n    \t\tthis.statusCode = statusCode;\n    \t\tthis.message = message;\n    \t\tthis.data = null;\n    \t\tthis.errors = errors;\n\n    \t\tif (stack) {\n    \t\t\tthis.stack = stack;\n    \t\t} else {\n    \t\t\tError.captureStackTrace(this, this.constructor);\n    \t\t}\n    \t}\n    }\n\n    export { ApiError };\n    ```\n\n4. **`custom-api-response`**:\n   Standardizes successful API responses.\n\n    **Code Snippet**:\n\n    ```js\n    class ApiResponse {\n    \tconstructor(statusCode, message = 'success', data) {\n    \t\tthis.statusCode = statusCode;\n    \t\tthis.message = message;\n    \t\tthis.data = data;\n    \t\tthis.success = statusCode \u003c 400;\n    \t}\n    }\n\n    export { ApiResponse };\n    ```\n\n5. **`multer-file-upload`**:\n   Sets up a file upload service using `multer`.\n\n    **Code Snippet**:\n\n    ```js\n    import multer from 'multer';\n\n    const storage = multer.diskStorage({\n    \tdestination: function (req, file, cb) {\n    \t\tcb(null, './public/temp');\n    \t},\n    \tfilename: function (req, file, cb) {\n    \t\tcb(null, file.originalname);\n    \t},\n    });\n\n    export const upload = multer({ storage });\n\n   ```\n6. **`mongoose-con`**:\n   Sets up a connection to your mongodb using `mongoose`.\n\n    **Code Snippet**:\n\n    ```js\n    import mongoose from 'mongoose';\n\n    function connectToDB(URI) {\n    \tmongoose\n    \t\t.connect(URI)\n    \t\t.then(() =\u003e {\n    \t\t\tconsole.log('Connection to the db succesful');\n    \t\t})\n    \t\t.catch((err) =\u003e {\n    \t\t\tconsole.error('An error occcured : ', err);\n    \t\t});\n    }\n    export default connectToDB;\n\n\n   ```\n7. **`mongoose-schema`**:\n   Sets up a basic schema for your db using `mongoose`.\n\n    **Code Snippet**:\n\n    ```js\n    import mongoose from 'mongoose';\n\n    const schema = new mongoose.Schema({\n    \tkey: String,\n    });\n\n    const model = mongoose.model('Model', schema);\n\n    export default model;\n    ```\n\n8. **`nodemailer`**:\n   Sets up email functionality in Node.js projects\n\n    **Code Snippet**:\n\n    ```js\n    const nodemailer = require('nodemailer');\n    require('dotenv').config();\n    const transporter = nodemailer.createTransport({\n    \tservice: 'gmail',\n    \tauth: {\n    \t\tuser: process.env.EMAIL,\n    \t\tpass: process.env.EMAIL_PASSWORD,\n    \t},\n    });\n    const mailOptions = {\n    \tfrom: process.env.EMAIL,\n    \tto: 'recipient@example.com',\n    \tsubject: 'Hello from Nodemailer',\n    \ttext: 'This is a plain text body!',\n    \thtml: '\u003cp\u003eThis is an \u003cb\u003eHTML\u003c/b\u003e body!\u003c/p\u003e',\n    };\n    transporter.sendMail(mailOptions, (error, info) =\u003e {\n    \tif (error) {\n    \t\treturn console.log(error);\n    \t}\n    \tconsole.log('Email sent: ' + info.response);\n    });\n    ```\n\n9. **`cloudinary-util`**\n   Sets up Cloudinary functionality in a Node.js project\n\n    **Code Snippet**:\n\n    ```js\n    import { v2 as cloudinary } from 'cloudinary';\n    import fs from 'fs';\n    // These values need to be defined in your environment variables (usually in a .env file)\n    cloudinary.config({\n    \tcloud_name: process.env.CLOUDINARY_CLOUD_NAME,\n    \tapi_key: process.env.CLOUDINARY_API_KEY,\n    \tapi_secret: process.env.CLOUDINARY_API_SECRET,\n    });\n\n    const uploadOnCloudinary = async (localFilePath) =\u003e {\n    \ttry {\n    \t\tif (!localFilePath) return null;\n\n    \t\tconst response = await cloudinary.uploader.upload(localFilePath, {\n    \t\t\tresource_type: 'auto',\n    \t\t});\n\n    \t\tfs.unlinkSync(localFilePath);\n    \t\treturn response;\n    \t} catch (error) {\n    \t\tfs.unlinkSync(localFilePath);\n    \t\treturn null;\n    \t}\n    };\n    export { uploadOnCloudinary };\n    ```\n\n### 3. `run generate-ai-snippet \u003csnippetName\u003e`\n\nWith the new AI-powered code generation feature, you can generate customized code snippets. For instance, to generate a code snippet for a specific backend functionality, you can run:\n\n```bash\nrun generate-ai-snippet \u003csnippetName\u003e\n```\n\nExample:\n\n```bash\nrun generate-ai-snippet login-controller\n```\n\nThis will generate a code snippet for login-controller using AI that looks like :\n\n```bash\nGenerated Code Snippet for login-controller:\n\nconst User = require('../models/User');\nconst bcrypt = require('bcrypt');\nconst jwt = require('jsonwebtoken');\n\nmodule.exports.login = async (req, res) =\u003e {\n  try {\n    const { email, password } = req.body;\n\n    const user = await User.findOne({ email });\n    if (!user) {\n      return res.status(401).json({ message: 'Invalid credentials' });\n    }\n\n    const isMatch = await bcrypt.compare(password, user.password);\n    if (!isMatch) {\n      return res.status(401).json({ message: 'Invalid credentials' });\n    }\n\n    const token = jwt.sign({ userId: user._id }, process.env.JWT_SECRET, { expiresIn: '1h' });\n    res.json({ token, user: { _id: user._id, name: user.name, email: user.email } });\n  } catch (err) {\n    console.error(err);\n    res.status(500).json({ message: 'Server error' });\n  }\n};\n\nThe code snippet is generated successfuly and may require some modifications to fit your use case.\n```\n\n## Full User Journey Example\n\nHere’s a complete example of a user journey, from project setup to injecting code snippets into the project.\n\n### Step 1: Install the CLI Globally\n\nFirst, install the tool using npm:\n\n```bash\nnpm install -g backend-generator-cli\n```\n\n### Step 2: Create a New Backend Project\n\nNavigate to your desired directory and run the following command to generate the project structure:\n\n```bash\nrun create-project\n```\n\nThis will create a new backend project with the following structure:\n\n```\n.\n├── src/\n│   ├── controllers/\n│   ├── db/\n│   ├── middlewares/\n│   ├── models/\n│   ├── routes/\n│   ├── utils/\n│   ├── app.js\n│   ├── constants.js\n│   └── index.js\n├── .env.sample\n├── .gitignore\n├── .prettierignore\n├── .prettierrc\n├── package.json\n└── README.md\n```\n\n### Step 3: Move to the `src/utils` Directory\n\nChange your working directory to the `src/utils` folder:\n\n```bash\ncd src\ncd utils\n```\n\nYou are now inside the `utils` folder where you will generate the file upload handler snippet.\n\n### Step 4: Add a Snippet to Handle File Uploads\n\nNext, add a `multer` file upload handler by running the following command:\n\n```bash\nrun generate-snippet multer-file-upload\n```\n\nThis command will create a new file called `multer-file-upload.js` in the `src/utils` directory, which is now your current working directory. The content of this file will look like this:\n\n```js\nimport multer from 'multer';\n\nconst storage = multer.diskStorage({\n\tdestination: function (req, file, cb) {\n\t\tcb(null, './public/temp');\n\t},\n\tfilename: function (req, file, cb) {\n\t\tcb(null, file.originalname);\n\t},\n});\n\nexport const upload = multer({ storage });\n```\n\n### Step 5: Use the Snippet in Your Project\n\nNow that the file upload handler has been generated in the `utils` folder, you can import and use it in your application. For instance, in `src/routes/uploadRoute.js`:\n\n```js\nimport express from 'express';\nimport { upload } from '../utils/multer-file-upload';\n\nconst router = express.Router();\n\nrouter.post('/upload', upload.single('file'), (req, res) =\u003e {\n\tres.send('File uploaded successfully');\n});\n\nexport default router;\n```\n\nMake sure that your main `app.js` or `index.js` includes this route:\n\n```js\nimport express from 'express';\nimport uploadRoute from './routes/uploadRoute';\n\nconst app = express();\n\napp.use('/api', uploadRoute);\n\napp.listen(3000, () =\u003e {\n\tconsole.log('Server is running on port 3000');\n});\n```\n\n### Step 6: Continue Building\n\nContinue building your application by adding your business logic, routes, controllers, and any other necessary components. Feel free to generate additional snippets like `custom-api-error` and `async-ops-handler` as needed.\n\nThis flow demonstrates how you can set up your backend project structure and utilize the code snippets generated by `backend-generator-cli` to accelerate your development.\n\n## Future Enhancements\n\n-   Add more predefined snippets for common backend use cases.\n-   Add a controller to get the most in-demand snippets.\n\n\n## Our Contributors\n\n-   We extend our heartfelt gratitude for your invaluable contribution to our project! Your efforts play a pivotal role in elevating this project to greater heights.\n-   Make sure you show some love by giving ⭐ to our repository.\n\n\u003cdiv align=\"center\"\u003e\n\n  \u003ca href=\"https://github.com/PranavBarthwal/backend-generator-cli\"\u003e\n    \u003cimg src=\"https://contrib.rocks/image?repo=PranavBarthwal/backend-generator-cli\u0026\u0026max=1000\" /\u003e\n  \u003c/a\u003e\n\u003c/div\u003e\n\n## License\n\nThis project is licensed under the MIT License. See the [LICENSE](LICENSE) file for more details.\n\n---\n\n\u003cbr\u003e\n\n\u003cdiv align=\"center\"\u003e\n  \u003cp\u003eMade with ❤️ by Pranav Barthwal\u003c/p\u003e\n  \u003cimg src=\"https://avatars.githubusercontent.com/u/110532770?v=4\" width=\"150\" style=\"border-radius: 50%;\" alt=\"Pranav Barthwal\" /\u003e\n  \u003cp\u003e\n    \u003ca href=\"https://github.com/PranavBarthwal\" target=\"_blank\"\u003eFollow me on GitHub\u003c/a\u003e |\n    \u003ca href=\"https://twitter.com/pranavbarthwal_\" target=\"_blank\"\u003eFollow me on X\u003c/a\u003e\n  \u003c/p\u003e\n\u003c/div\u003e\n\u003cp align=\"right\"\u003e\u003ca href=\"#top\"\u003eback to top\u003c/a\u003e\u003c/p\u003e\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpranavbarthwal%2Fbackend-generator-cli","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpranavbarthwal%2Fbackend-generator-cli","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpranavbarthwal%2Fbackend-generator-cli/lists"}