Certainly! Below is an updated version of your code snippet with additional features, including input validation and improved error handling:
const express = require('express');
const axios = require('axios');
const app = express();
// Middleware to parse JSON request bodies
app.use(express.json());
// Utility function to validate the input object
function validateInput(input) {
// Example: Replace with actual validation logic
if (!input || typeof input !== 'object') {
return 'Input must be a valid object';
}
if (!input.requiredField) {
return 'requiredField is missing';
}
// Add more validation rules as needed
return null;
}
app.post("/mock", async (req, res) => {
const inputObject = req.body;
// Validate the input
const validationError = validateInput(inputObject);
if (validationError) {
return res.status(400).json({
status: "failure",
error: validationError,
});
}
try {
const response = await axios.post("https://easygo-grf6.onrender.com/mock", inputObject);
return res.json({
status: "success",
data: response.data,
created_date: new Date(),
});
} catch (error) {
console.error("Error making POST request:", error);
// Check if the error is an Axios error with a response
if (error.response) {
return res.status(error.response.status).json({
status: "failure",
error: error.response.data || "An error occurred on the server",
});
}
// Handle request errors (e.g., network issues)
return res.status(500).json({
status: "failure",
error: "An internal server error occurred",
});
}
});
// Example server setup (adjust port as needed)
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
Changes Made:
-
Input Validation: Added a utility function validateInput that checks if the input object meets certain criteria. Modify this function according to your validation requirements.
-
Error Handling:
- Improved error handling by checking for Axios-specific errors and differentiating between server-side errors and network issues.
- Sends appropriate HTTP status codes for different error scenarios.
-
JSON Parsing Middleware: Ensures that the request payload is parsed as JSON using the express.json() middleware.
Make sure to update the validateInput function as per your actual requirements, specifying the necessary fields and validation logic relevant to your application.