Here is the source code that implements the features described in your object, along with a JSON response format that includes the generated code.
Generated Code
// Import required packages
const express = require('express');
const rateLimit = require('express-rate-limit');
const helmet = require('helmet');
const cors = require('cors');
// Create an Express application
const app = express();
// Middleware for security headers
app.use(helmet());
// Enable CORS for universal access
app.use(cors());
// Rate limiting middleware
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100 // Limit each IP to 100 requests per windowMs
});
// Apply rate limiting to all requests
app.use(limiter);
// Sample route
app.get('/', (req, res) => {
res.send('Hello World!');
});
// Error handling middleware
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({ message: 'Something went wrong!' });
});
// Start server and listen on port 4000
const PORT = process.env.PORT || 4000;
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
JSON Response Format
{
"name": "prompt_name",
"schema": {
"type": "string",
"code": "// Import required packages\nconst express = require('express');\nconst rateLimit = require('express-rate-limit');\nconst helmet = require('helmet');\nconst cors = require('cors');\n\n// Create an Express application\nconst app = express();\n\n// Middleware for security headers\napp.use(helmet());\n\n// Enable CORS for universal access\napp.use(cors());\n\n// Rate limiting middleware\nconst limiter = rateLimit({\n windowMs: 15 * 60 * 1000, // 15 minutes\n max: 100 // Limit each IP to 100 requests per windowMs\n});\n\n// Apply rate limiting to all requests\napp.use(limiter);\n\n// Sample route\napp.get('/', (req, res) => {\n res.send('Hello World!');\n});\n\n// Error handling middleware\napp.use((err, req, res, next) => {\n console.error(err.stack);\n res.status(500).json({ message: 'Something went wrong!' });\n});\n\n// Start server and listen on port 4000\nconst PORT = process.env.PORT || 4000;\napp.listen(PORT, () => {\n console.log(`Server is running on http://localhost:${PORT}`);\n});"
}
}
Explanation
- Express Server Setup: Creates an Express app listening on port 4000.
- Rate Limiting: Implements a rate limiter that restricts requests to a maximum of 100 per 15 minutes.
- Security Middleware: Uses Helmet to set various HTTP headers for security.
- CORS: Enables Cross-Origin Resource Sharing for all routes.
- Error Handling: Captures any errors that occur in the application and responds with a JSON object.
You can use the generated code as a reference to set up your Express server with these features.