Skip to content

Commit

Permalink
Refactor fetchData to support dynamic query parameters and update App…
Browse files Browse the repository at this point in the history
….js to use new fetchData structure

- Updated fetchData.js to build URLs dynamically with query parameters
- Modified App.js to pass query parameters to fetchData for fetching environment details
- Improved error handling for fetch requests
  • Loading branch information
Samyak Rout committed Nov 14, 2024
1 parent 64e3814 commit 19b71cb
Show file tree
Hide file tree
Showing 9 changed files with 117 additions and 31 deletions.
19 changes: 15 additions & 4 deletions infra_env_dashboard/backend/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import (
companyRouter "backend/services/fetch_company_details/router" // Import Company Router
infraRouter "backend/services/fetch_infra_types/router" // Import Infra Router
internalEnvRouter "backend/services/fetch_internal_env_details/router" // Import Internal Env Router
"fmt"
"os"

_ "backend/docs" // Import Swagger docs

Expand Down Expand Up @@ -53,9 +55,18 @@ func main() {
internalEnvRouter.SetupInternalEnvRoutes(api, db)
}

// Start the server on port 8080
logger.Logger.Info("Server running on port 8080")
if err := router.Run(":8080"); err != nil {
// Get the port from environment variable or use default
port := os.Getenv("PORT")
if port == "" {
port = "8080" // Default port if not specified
}

// Log where the server will run
host := "0.0.0.0" // This makes it accessible on any host interface (suitable for cloud and local)
logger.Logger.Infof("Server running on %s:%s", host, port)

// Start the server
if err := router.Run(fmt.Sprintf("%s:%s", host, port)); err != nil {
logger.Logger.Fatalf("Failed to run server: %v", err)
}
}
}
37 changes: 37 additions & 0 deletions infra_env_dashboard/frontend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

13 changes: 3 additions & 10 deletions infra_env_dashboard/frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,7 @@
"test": "echo \"Error: no test specified\" && exit 1"
},
"proxy": {
"/api/company": {
"target": "http://localhost:8080",
"changeOrigin": true
},
"/api/infra-types": {
"target": "http://localhost:8081",
"changeOrigin": true
},
"/api/internal-env-details": {
"/api": {
"target": "http://localhost:8080",
"changeOrigin": true
}
Expand All @@ -37,9 +29,10 @@
"@babel/preset-env": "^7.26.0",
"@babel/preset-react": "^7.25.9",
"babel-loader": "^9.2.1",
"dotenv-webpack": "^8.1.0",
"html-webpack-plugin": "^5.6.3",
"webpack": "^5.96.1",
"webpack-cli": "^5.1.4",
"webpack-dev-server": "^5.1.0"
}
}
}
17 changes: 8 additions & 9 deletions infra_env_dashboard/frontend/src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,30 +5,29 @@ import Header from "./components/Header";
import Sidebar from "./components/Sidebar";
import MainContent from "./components/MainContent";
import Footer from "./components/Footer";
import { fetchData } from "./services/fetchData";
import "./styles/App.css";

function App() {
const [selectedEnvironment, setSelectedEnvironment] = useState(null);
const [envDetails, setEnvDetails] = useState([]);

// Function to fetch environment details based on selected product and environment name
const fetchEnvDetails = async (product, envName) => {
try {
const response = await fetch(`http://localhost:8080/api/internal-env-details?product=${encodeURIComponent(product)}&group=${encodeURIComponent(envName)}`);
const data = await response.json();
setEnvDetails(data.environmentDetails || []); // Store environment details
// Pass parameters as an object to fetchData
const data = await fetchData("fetchInternalEnvDetails", { product, group: envName });
setEnvDetails(data.environmentDetails || []);
} catch (error) {
console.error("Failed to fetch environment details:", error);
setEnvDetails([]); // Clear details if fetch fails
setEnvDetails([]);
}
};

// Handle environment selection
const handleEnvironmentSelect = (section, product, environment) => {
if (product && environment) { // Ensure both product and environment are available
if (product && environment) {
console.log(`Selected environment: ${environment} for product: ${product}`);
setSelectedEnvironment({ product, environment });
fetchEnvDetails(product, environment); // Fetch details for the selected environment
fetchEnvDetails(product, environment);
} else {
console.warn("Product or environment is missing in the selection");
}
Expand All @@ -39,7 +38,7 @@ function App() {
<Header />
<div className="main-layout">
<Sidebar onEnvironmentSelect={handleEnvironmentSelect} />
<MainContent envDetails={envDetails} /> {/* Pass envDetails to MainContent */}
<MainContent envDetails={envDetails} />
</div>
<Footer />
</div>
Expand Down
3 changes: 2 additions & 1 deletion infra_env_dashboard/frontend/src/components/Header.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import React, { useEffect, useState } from "react";
import "../styles/Header.css";
import config from "../config"; // Import the config

const Header = () => {
const [companyName, setCompanyName] = useState("Loading...");
Expand All @@ -10,7 +11,7 @@ const Header = () => {
console.log("Starting to fetch company name..."); // Debug log: Start of fetch

// Fetch company name from the API
fetch('http://localhost:8080/api/company')
fetch(config.fetchCompanyDetails)
.then((response) => {
console.log("API response received:", response); // Debug log: API response
if (!response.ok) {
Expand Down
18 changes: 14 additions & 4 deletions infra_env_dashboard/frontend/src/config.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,17 @@
// config.js

// Set default values for API_HOST and API_PORT
const API_HOST = process.env.REACT_APP_API_HOST || "http://localhost";
const API_PORT = process.env.REACT_APP_API_PORT || "8080";

// Construct the base API URL
const API_BASE_URL = `${API_HOST}:${API_PORT}/api`;

// Export config with dynamically constructed URLs
const config = {
fetchCompanyDetails: "http://localhost:8080/api",
fetchInfraTypes: "http://localhost:8080/api",
fetchInternalEnvDetails: "http://localhost:8080/api",
fetchCompanyDetails: `${API_BASE_URL}/company`,
fetchInfraTypes: `${API_BASE_URL}/infra-types`,
fetchInternalEnvDetails: `${API_BASE_URL}/internal-env-details`,
};

export default config;
export default config;
4 changes: 2 additions & 2 deletions infra_env_dashboard/frontend/src/services/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import config from "../config";
// Fetch company details
export const fetchCompanyDetails = async () => {
try {
const response = await fetch(`${config.fetchCompanyDetails}/company`);
const response = await fetch(`${config.fetchCompanyDetails}`);
if (!response.ok) throw new Error("Failed to fetch company details");
const data = await response.json();
return data;
Expand All @@ -16,7 +16,7 @@ export const fetchCompanyDetails = async () => {
// Fetch infrastructure types
export const fetchInfraTypes = async () => {
try {
const response = await fetch(`${config.fetchInfraTypes}/infra-types`);
const response = await fetch(`${config.fetchInfraTypes}`);
if (!response.ok) throw new Error("Failed to fetch infra types");
const data = await response.json();
return data.infraTypes || [];
Expand Down
33 changes: 33 additions & 0 deletions infra_env_dashboard/frontend/src/services/fetchData.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// src/services/fetchData.js

import config from "../config";

export async function fetchData(endpointKey, params = {}) {
// Get the base URL based on the endpoint key in config
const baseUrl = config[endpointKey];
if (!baseUrl) {
throw new Error(`Invalid endpoint key: ${endpointKey}`);
}

// Construct the full URL with query parameters
const url = new URL(baseUrl);
Object.keys(params).forEach(key => {
if (params[key]) {
url.searchParams.append(key, params[key]);
}
});

try {
// Perform the fetch call with the constructed URL
const response = await fetch(url.toString());
if (!response.ok) {
throw new Error(`Error: ${response.statusText}`);
}

// Return the parsed JSON data
return await response.json();
} catch (error) {
console.error(`Failed to fetch data from ${url}:`, error);
throw error;
}
}
4 changes: 3 additions & 1 deletion infra_env_dashboard/frontend/webpack.config.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const Dotenv = require('dotenv-webpack');

module.exports = {
entry: './src/index.js',
Expand Down Expand Up @@ -31,7 +32,8 @@ module.exports = {
new HtmlWebpackPlugin({
template: './src/index.html',
filename: 'index.html'
})
}),
new Dotenv() // Load environment variables from a .env file
],
devServer: {
static: './dist',
Expand Down

0 comments on commit 19b71cb

Please sign in to comment.