From 76509f30049da6c1fa038f43105ab1298a727838 Mon Sep 17 00:00:00 2001 From: Amit Date: Sun, 13 Oct 2024 00:39:12 +0530 Subject: [PATCH] Added new snippet: Rate Limit Middleware --- README.md | 219 ++++++++++++++++-------------- snippets/rate-limit-middleware.js | 9 ++ 2 files changed, 128 insertions(+), 100 deletions(-) create mode 100644 snippets/rate-limit-middleware.js diff --git a/README.md b/README.md index 3473242..0aea0f6 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,7 @@ # Backend Generator CLI + > **Now supporting AI powered code snippet generation!** 🚀 ![npm](https://img.shields.io/npm/dt/backend-generator-cli?color=brightgreen&label=Total%20Downloads&style=for-the-badge) ![npm](https://img.shields.io/npm/dw/backend-generator-cli?color=blue&label=Weekly%20Downloads&style=for-the-badge) @@ -9,21 +10,22 @@ ## Key Features -- **Instant Backend Setup**: Generate a clean, well-organized backend project structure with a single command. -- **Best Practices Built-in**: The generated project follows industry-standard best practices for scalable backend development. -- **Custom Code Snippets**: Insert predefined code snippets such as API error handling, file uploading, and more using simple CLI commands. -- **AI-powered Custom Code Snippets**: Generate customizable code snippets using Generative AI with simple CLI commands. -- **Modular and Extensible**: The tool allows you to customize and expand the project structure to meet your specific needs. +- **Instant Backend Setup**: Generate a clean, well-organized backend project structure with a single command. +- **Best Practices Built-in**: The generated project follows industry-standard best practices for scalable backend development. +- **Custom Code Snippets**: Insert predefined code snippets such as API error handling, file uploading, and more using simple CLI commands. +- **AI-powered Custom Code Snippets**: Generate customizable code snippets using Generative AI with simple CLI commands. +- **Modular and Extensible**: The tool allows you to customize and expand the project structure to meet your specific needs. ## Index -- [Installation](#installation) -- [Commands](#commands) - - [1. run create-project](#1-run-create-project) - - [2. run generate-snippet](#2-run-generate-snippet-snippet-name) - - [3. run generate-ai-snippet](#3-run-generate-ai-snippet-snippetname) -- [Full User Journey Example](#full-user-journey-example) -- [Future Enhancements](#future-enhancements) -- [License](#license) + +- [Installation](#installation) +- [Commands](#commands) + - [1. run create-project](#1-run-create-project) + - [2. run generate-snippet](#2-run-generate-snippet-snippet-name) + - [3. run generate-ai-snippet](#3-run-generate-ai-snippet-snippetname) +- [Full User Journey Example](#full-user-journey-example) +- [Future Enhancements](#future-enhancements) +- [License](#license) --- @@ -40,6 +42,7 @@ After installation, you will have access to two main commands: `create-project` ## Commands ### 1. `run create-project` + Generate a new backend project with a pre-configured folder structure: ```bash @@ -72,7 +75,7 @@ This structure is clean, easy to navigate, and ready to be extended with your ow ### 2. `run generate-snippet ` -Generate and inject predefined code snippets into your project. Snippets are placed in individual files in your current working directory. +Generate and inject predefined code snippets into your project. Snippets are placed in individual files in your current working directory. Example: @@ -87,121 +90,138 @@ This command will create a new file `multer-file-upload.js` in the current worki 1. **`async-ops-handler`**: Handles asynchronous operations with error handling. - **Code Snippet**: - ```js + **Code Snippet**: + + ```js const asyncHandler = (requestHandler) => { - return (req, res, next) => { - Promise - .resolve(requestHandler(req, res, next)) - .catch((err) => next(err)) - } - } + return (req, res, next) => { + Promise.resolve(requestHandler(req, res, next)).catch((err) => next(err)); + }; + }; - export { asyncHandler } - ``` + export { asyncHandler }; + ``` 2. **`custom-api-error`**: Standardizes error responses for your API. - **Code Snippet**: - ```js - class ApiError extends Error{ - constructor( - statusCode, - message= "Something went wrong", - errors=[], - stack="" - ){ - super(message); - this.statusCode = statusCode; - this.message = message; - this.data = null; - this.errors = errors; - - if(stack){ - this.stack = stack; - }else{ - Error.captureStackTrace(this, this.constructor); - } - } + **Code Snippet**: + + ```js + class ApiError extends Error { + constructor(statusCode, message = 'Something went wrong', errors = [], stack = '') { + super(message); + this.statusCode = statusCode; + this.message = message; + this.data = null; + this.errors = errors; + + if (stack) { + this.stack = stack; + } else { + Error.captureStackTrace(this, this.constructor); + } + } } - export { ApiError } - ``` + export { ApiError }; + ``` 3. **`custom-api-response`**: Standardizes successful API responses. - **Code Snippet**: - ```js - class ApiResponse{ - constructor(statusCode, message="success", data){ - this.statusCode = statusCode; - this.message = message; - this.data = data; - this.success = statusCode < 400; - } + **Code Snippet**: + + ```js + class ApiResponse { + constructor(statusCode, message = 'success', data) { + this.statusCode = statusCode; + this.message = message; + this.data = data; + this.success = statusCode < 400; + } } - export {ApiResponse} - ``` + export { ApiResponse }; + ``` 4. **`multer-file-upload`**: Sets up a file upload service using `multer`. - **Code Snippet**: - ```js - import multer from "multer"; + **Code Snippet**: + + ```js + import multer from 'multer'; const storage = multer.diskStorage({ - destination: function(req, file, cb){ - cb(null, './public/temp'); - }, - filename: function(req, file, cb){ - cb(null, file.originalname); - } + destination: function (req, file, cb) { + cb(null, './public/temp'); + }, + filename: function (req, file, cb) { + cb(null, file.originalname); + }, }); export const upload = multer({ storage }); + ``` - ``` 5. **`mongoose-con`**: Sets up a connection to your mongodb using `mongoose`. - **Code Snippet**: - ```js - import mongoose from 'mongoose'; + **Code Snippet**: + + ```js + import mongoose from 'mongoose'; - function connectToDB(URI) { - mongoose.connect(URI).then(() => { - console.log("Connection to the db succesful"); - }).catch(err => { - console.error("An error occcured : ",err); - }) + function connectToDB(URI) { + mongoose + .connect(URI) + .then(() => { + console.log('Connection to the db succesful'); + }) + .catch((err) => { + console.error('An error occcured : ', err); + }); } export default connectToDB; + ``` - - ``` 6. **`mongoose-schema`**: Sets up a basic schema for your db using `mongoose`. - **Code Snippet**: - ```js + **Code Snippet**: + + ```js import mongoose from 'mongoose'; const schema = new mongoose.Schema({ - key:String, + key: String, }); - const model = mongoose.model("Model",schema); + const model = mongoose.model('Model', schema); export default model; + ``` - ``` +7. **`rate-limit-middleware`**: + Sets up a rate limit middleware using `express-rate-limit`. + **Code Snippet**: + + ```js + import rateLimit from 'express-rate-limit'; + + const limiter = rateLimit({ + windowMs: 15 * 60 * 1000, + max: 1000, + message: 'Too many requests from this IP, please try again after 15 minutes.', + }); + + export default limiter; + ``` ### 3. `run generate-ai-snippet ` + With 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: ```bash @@ -215,6 +235,7 @@ run generate-ai-snippet login-controller ``` This will generate a code snippet for login-controller using AI that looks like : + ```bash Generated Code Snippet for login-controller: @@ -240,7 +261,7 @@ module.exports.login = async (req, res) => { res.json({ token, user: { _id: user._id, name: user.name, email: user.email } }); } catch (err) { console.error(err); - res.status(500).json({ message: 'Server error' }); + res.status(500).json({ message: 'Server error' }); } }; @@ -314,12 +335,12 @@ This command will create a new file called `multer-file-upload.js` in the `src/u import multer from 'multer'; const storage = multer.diskStorage({ - destination: function (req, file, cb) { - cb(null, './public/temp'); - }, - filename: function (req, file, cb) { - cb(null, file.originalname); - } + destination: function (req, file, cb) { + cb(null, './public/temp'); + }, + filename: function (req, file, cb) { + cb(null, file.originalname); + }, }); export const upload = multer({ storage }); @@ -336,7 +357,7 @@ import { upload } from '../utils/multer-file-upload'; const router = express.Router(); router.post('/upload', upload.single('file'), (req, res) => { - res.send('File uploaded successfully'); + res.send('File uploaded successfully'); }); export default router; @@ -353,7 +374,7 @@ const app = express(); app.use('/api', uploadRoute); app.listen(3000, () => { - console.log('Server is running on port 3000'); + console.log('Server is running on port 3000'); }); ``` @@ -363,17 +384,15 @@ Continue building your application by adding your business logic, routes, contro This 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. - ## Future Enhancements -- Add more predefined snippets for common backend use cases. -- Add a controller to get the most in-demand snippets. - +- Add more predefined snippets for common backend use cases. +- Add a controller to get the most in-demand snippets. ## Our Contributors -- 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. -- Make sure you show some love by giving ⭐ to our repository. +- 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. +- Make sure you show some love by giving ⭐ to our repository.
@@ -382,12 +401,12 @@ This flow demonstrates how you can set up your backend project structure and uti
- ## License This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for more details. --- +
diff --git a/snippets/rate-limit-middleware.js b/snippets/rate-limit-middleware.js new file mode 100644 index 0000000..862fc05 --- /dev/null +++ b/snippets/rate-limit-middleware.js @@ -0,0 +1,9 @@ +import rateLimit from 'express-rate-limit'; + +const limiter = rateLimit({ + windowMs: 15 * 60 * 1000, + max: 1000, + message: 'Too many requests from this IP, please try again after 15 minutes.', +}); + +export default limiter;