|
| 1 | +# @th3hero/request-validator Examples |
| 2 | + |
| 3 | +## 🚀 Real-World Usage Examples |
| 4 | + |
| 5 | +### E-commerce API Validation |
| 6 | + |
| 7 | +```typescript |
| 8 | +import { validateInput } from '@th3hero/request-validator'; |
| 9 | +import { Request } from 'express'; |
| 10 | + |
| 11 | +// Product creation validation |
| 12 | +const productRules = { |
| 13 | + name: 'required|min:3|max:100', |
| 14 | + price: 'required|numeric|min:0', |
| 15 | + category: 'required|in:electronics,clothing,books,home', |
| 16 | + description: 'max:500', |
| 17 | + images: 'file|mimetype:image/jpeg,image/png|max:5', |
| 18 | + sku: 'required|unique:products,sku', |
| 19 | + stock: 'integer|min:0' |
| 20 | +}; |
| 21 | + |
| 22 | +app.post('/products', async (req: Request, res) => { |
| 23 | + const result = await validateInput(req, productRules); |
| 24 | + |
| 25 | + if (result.failed) { |
| 26 | + return res.status(400).json({ |
| 27 | + success: false, |
| 28 | + errors: result.errors |
| 29 | + }); |
| 30 | + } |
| 31 | + |
| 32 | + // Create product... |
| 33 | + res.status(201).json({ success: true, product: newProduct }); |
| 34 | +}); |
| 35 | +``` |
| 36 | + |
| 37 | +### User Registration with Custom Validators |
| 38 | + |
| 39 | +```typescript |
| 40 | +const customValidators = { |
| 41 | + isStrongPassword: (value: string) => { |
| 42 | + const hasUpperCase = /[A-Z]/.test(value); |
| 43 | + const hasLowerCase = /[a-z]/.test(value); |
| 44 | + const hasNumbers = /\d/.test(value); |
| 45 | + const hasSpecialChar = /[!@#$%^&*(),.?":{}|<>]/.test(value); |
| 46 | + |
| 47 | + if (!hasUpperCase || !hasLowerCase || !hasNumbers || !hasSpecialChar) { |
| 48 | + return 'Password must contain uppercase, lowercase, number, and special character'; |
| 49 | + } |
| 50 | + return true; |
| 51 | + }, |
| 52 | + |
| 53 | + isAdult: (value: string) => { |
| 54 | + const age = parseInt(value); |
| 55 | + const today = new Date(); |
| 56 | + const birthDate = new Date(value); |
| 57 | + const ageDiff = today.getFullYear() - birthDate.getFullYear(); |
| 58 | + |
| 59 | + return ageDiff >= 18 || 'Must be at least 18 years old'; |
| 60 | + } |
| 61 | +}; |
| 62 | + |
| 63 | +const registrationRules = { |
| 64 | + username: 'required|min:3|max:20|unique:users,username', |
| 65 | + email: 'required|email|unique:users,email', |
| 66 | + password: 'required|min:8|isStrongPassword', |
| 67 | + confirmPassword: 'required|same:password', |
| 68 | + birthDate: 'required|date|isAdult', |
| 69 | + terms: 'required|accepted' |
| 70 | +}; |
| 71 | + |
| 72 | +app.post('/register', async (req: Request, res) => { |
| 73 | + const result = await validateInput(req, { |
| 74 | + ...registrationRules, |
| 75 | + customValidators |
| 76 | + }); |
| 77 | + |
| 78 | + if (result.failed) { |
| 79 | + return res.status(400).json({ errors: result.errors }); |
| 80 | + } |
| 81 | + |
| 82 | + // Create user account... |
| 83 | +}); |
| 84 | +``` |
| 85 | + |
| 86 | +### File Upload with Multiple Types |
| 87 | + |
| 88 | +```typescript |
| 89 | +const uploadRules = { |
| 90 | + profilePicture: 'file|mimetype:image/jpeg,image/png|max:2', |
| 91 | + documents: 'file|mimetype:application/pdf,application/msword|max:10', |
| 92 | + video: 'file|mimetype:video/mp4,video/avi|max:50' |
| 93 | +}; |
| 94 | + |
| 95 | +app.post('/upload', async (req: Request, res) => { |
| 96 | + const result = await validateInput(req, uploadRules); |
| 97 | + |
| 98 | + if (result.failed) { |
| 99 | + return res.status(400).json({ errors: result.errors }); |
| 100 | + } |
| 101 | + |
| 102 | + // Process uploads... |
| 103 | + const files = result.data; |
| 104 | + // files.profilePicture, files.documents, files.video |
| 105 | +}); |
| 106 | +``` |
| 107 | + |
| 108 | +### API Rate Limiting with Validation |
| 109 | + |
| 110 | +```typescript |
| 111 | +const apiKeyRules = { |
| 112 | + 'x-api-key': 'required|exists:api_keys,key', |
| 113 | + 'x-user-id': 'required|exists:users,id' |
| 114 | +}; |
| 115 | + |
| 116 | +app.use('/api/*', async (req: Request, res, next) => { |
| 117 | + const result = await validateInput(req, apiKeyRules); |
| 118 | + |
| 119 | + if (result.failed) { |
| 120 | + return res.status(401).json({ |
| 121 | + error: 'Invalid API credentials', |
| 122 | + details: result.errors |
| 123 | + }); |
| 124 | + } |
| 125 | + |
| 126 | + // Add user info to request |
| 127 | + req.user = result.data; |
| 128 | + next(); |
| 129 | +}); |
| 130 | +``` |
| 131 | + |
| 132 | +### Form Validation with Conditional Rules |
| 133 | + |
| 134 | +```typescript |
| 135 | +const surveyRules = { |
| 136 | + name: 'required|min:2', |
| 137 | + email: 'required|email', |
| 138 | + age: 'required|integer|min:13', |
| 139 | + occupation: 'required|in:student,employed,unemployed,retired', |
| 140 | + salary: 'required_if:occupation,employed|numeric|min:0', |
| 141 | + education: 'required_if:occupation,student|in:high_school,college,university', |
| 142 | + interests: 'array|min:1|max:5' |
| 143 | +}; |
| 144 | + |
| 145 | +app.post('/survey', async (req: Request, res) => { |
| 146 | + const result = await validateInput(req, surveyRules); |
| 147 | + |
| 148 | + if (result.failed) { |
| 149 | + return res.status(400).json({ errors: result.errors }); |
| 150 | + } |
| 151 | + |
| 152 | + // Process survey... |
| 153 | +}); |
| 154 | +``` |
| 155 | + |
| 156 | +### Database-Driven Validation |
| 157 | + |
| 158 | +```typescript |
| 159 | +// Set up database connection |
| 160 | +import { setDatabase } from '@th3hero/request-validator'; |
| 161 | +import mysql from 'mysql'; |
| 162 | + |
| 163 | +const pool = mysql.createPool({ |
| 164 | + host: process.env.DB_HOST, |
| 165 | + user: process.env.DB_USER, |
| 166 | + password: process.env.DB_PASSWORD, |
| 167 | + database: process.env.DB_NAME |
| 168 | +}); |
| 169 | + |
| 170 | +setDatabase(pool); |
| 171 | + |
| 172 | +// Validation with database checks |
| 173 | +const orderRules = { |
| 174 | + productId: 'required|exists:products,id', |
| 175 | + userId: 'required|exists:users,id', |
| 176 | + quantity: 'required|integer|min:1', |
| 177 | + shippingAddress: 'required|min:10' |
| 178 | +}; |
| 179 | + |
| 180 | +app.post('/orders', async (req: Request, res) => { |
| 181 | + const result = await validateInput(req, orderRules); |
| 182 | + |
| 183 | + if (result.failed) { |
| 184 | + return res.status(400).json({ errors: result.errors }); |
| 185 | + } |
| 186 | + |
| 187 | + // Create order... |
| 188 | +}); |
| 189 | +``` |
| 190 | + |
| 191 | +## 🎯 Best Practices Demonstrated |
| 192 | + |
| 193 | +1. **Specific Validation Rules**: Use detailed rules instead of generic ones |
| 194 | +2. **Custom Validators**: For complex business logic |
| 195 | +3. **Database Integration**: For data integrity |
| 196 | +4. **File Upload Security**: Proper MIME type validation |
| 197 | +5. **Error Handling**: Consistent error responses |
| 198 | +6. **Conditional Validation**: Based on other field values |
| 199 | + |
| 200 | +## 📚 More Examples |
| 201 | + |
| 202 | +<!-- Link to Express.js Integration Examples removed --> |
| 203 | +<!-- Link to Next.js API Routes removed --> |
| 204 | +<!-- Link to Fastify Plugin Examples removed --> |
| 205 | +<!-- Link to Testing Examples removed --> |
0 commit comments