Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Worked on mock server payload button #9

Merged
merged 7 commits into from
Jan 17, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 85 additions & 0 deletions apps/backend/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ import {
import { retailRouter } from "./controllers/retail";
import { sendUpsolicieatedOnStatus } from "./lib/utils/sendUpsolicieatedOnStatus";
import { loadConfig } from "./lib/utils";
import 'dotenv/config'
import path from 'path';
import { sub } from 'date-fns/fp';
const fs = require('fs');


export const app: Express = express();
Expand Down Expand Up @@ -71,6 +75,87 @@ app.use("/services", errorHandlingWrapper(servicesRouter));
app.use("/subscription", errorHandlingWrapper(subscriptionRouter));
app.use("/logistics", errorHandlingWrapper(logisticsRouter));
app.use("/agri", errorHandlingWrapper(agriRouter));
app.use("/get-data", async (req, res) => {
// console.log("action",req.query,__dirname)
let { action, domain, subdomain,version } = req.query
console.log("---->",action, domain, subdomain,version)
let baseDir=""
switch (domain) {
case "agri":
baseDir = (subdomain === "ONDC:AGR11") ? path.join(__dirname, `../domain-repos/@${domain}/draft-agri_output/api/components/Examples/Agri_Bids_And_Auction/${action}/`) : path.join(__dirname, `../domain-repos/@${domain}/draft-agri_input/api/components/Examples/Agri_Products/${action}/`)
break;
case "logistics":
baseDir = (subdomain === "ONDC:LOG10")?path.join(__dirname, `../domain-repos/@${domain}/draft-2.x/api/components/Examples/B2B_Dom_Logistics/${action}/`):path.join(__dirname, `../domain-repos/@${domain}/draft-2.x/api/components/Examples/B2B_Int_Logistics/${action}/`)
break;
case "services":
switch (subdomain) {
case "ONDC:SRV11":
baseDir = path.join(__dirname, `../domain-repos/@${domain}/draft-services/api/components/Examples/Services_home_service/${action}/`)
break
case "ONDC:SRV13":
baseDir = path.join(__dirname, `../domain-repos/@${domain}/draft-healthcare-service/api/components/Examples/Health_care_services/${action}/`)
break;
case "ONDC:SRV16":
baseDir = path.join(__dirname, `../domain-repos/@${domain}/draft-astro/api/components/Examples/Astro_services/${action}/`)
break;
case "ONDC:SRV14":
baseDir = path.join(__dirname, `../domain-repos/@${domain}/draft-agri-services/api/components/Examples/Agriculture_services/${action}/`)
break
case "ONDC:SRV18":
baseDir = path.join(__dirname, `../domain-repos/@${domain}/draft-agri_bids_and_auction/api/components/Examples/Agri_Bids_And_Auction/${action}/`)
break;
case "ONDC:SRV18":
baseDir = path.join(__dirname, `../domain-repos/@${domain}/draft-agri_equipment/api/components/Examples/Agri_Equipment_Hiring/${action}/`)
break
}
break;
case "retail":
baseDir = (version==="b2c")?path.join(__dirname, `../domain-repos/@${domain}-b2b/b2c_exports_2.0/api/components/Examples/B2C_Exports_Json/${action}/`):path.join(__dirname, `../domain-repos/@${domain}-b2b/release-2.0.2/api/components/Examples/B2B_json/${action}/`)
break;
case "subscription":
baseDir = path.join(__dirname, `../domain-repos/@mec/draft-print_media/api/components/Examples/Print_Content/${action}/`)
break;
}
try {
// Read all files in the directory
const files = fs.readdirSync(baseDir);

// Find the first JSON file in the directory
const jsonFile = files.find((file:any) => file.endsWith(".json"));

if (jsonFile) {
// Construct the full file path
const filePath = path.join(baseDir, jsonFile);
console.log("File path:", filePath);

// Read the content of the JSON file
fs.readFile(filePath, "utf8", (err:any, data:any) => {
if (err) {
console.error("Error reading file:", err);
return res.status(500).send({ error: "Error reading file" });
}

try {
// Parse JSON and send as a response
const jsonData = JSON.parse(data);
res.send({ data: jsonData });
} catch (parseError) {
console.error("Error parsing JSON:", parseError);
res.status(500).send({ error: "Invalid JSON format in the file" });
}
});

} else {
res.send({ data: "No file exist for this" });
// throw new Error(`No JSON file found in directory: ${baseDir}`);
}


} catch (error) {
console.log(error)
}

})
app.use("/detect_app_installation", (req: Request, res: Response) => {
const headers = req.headers;
return res.json({
Expand Down
129 changes: 121 additions & 8 deletions apps/frontend/src/components/MockRequestSection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,16 @@ import Grid from "@mui/material/Grid";
import Paper from "@mui/material/Paper";
import Stack from "@mui/material/Stack";
import Typography from "@mui/material/Typography";
import AddIcon from "@mui/icons-material/Add";
import { useEffect, useState } from "react";
import { CurlDisplay } from ".";
import { useAction, useDomain, useMock } from "../utils/hooks";
import { URL_MAPPING } from "../utils";
import { All_Actions, ALL_SUB_DOMAINS, URL_MAPPING } from "../utils";
import axios, { AxiosError } from "axios";
import { UserGuide } from "./UserGuideSection";
import { VITE_SERVER_URL } from "../utils/env";
import { Fab } from "@mui/material";
import { VERSION } from "lodash";

// type MockRequestSectionProp = {
// domain: string;
Expand All @@ -34,14 +37,46 @@ export const MockRequestSection = () => {

const { domain } = useDomain();
const [version, setVersion] = useState("");
const [show, setshow] = useState(false);
const [Action, setAction] = useState("");
const [Domain, setDomain] = useState("");
const { action, detectAction, logError, scenarios, setLogError } =
useAction();
const { setAsyncResponse, setSyncResponse } = useMock();

useEffect(() => {
setLog("");
setLogError(false);

}, [domain]);

async function call() {
const response = await axios.get("http://localhost:3000/get-data",{
params: {
action: Action.toLowerCase(),
domain: domain,
subdomain:Domain,
version:version
}
});
return response;
}
// console.log(domain,"Domainnn")
useEffect(() => {
console.log("ACTION CHANGED:", Action);

const fetchData = async () => {
const data = await call();
if (data.data.data) {
console.log("Response from backend:", data);
setLog(JSON.stringify(data.data.data))
detectAction(JSON.stringify(data.data.data) , version);
}
};

if(Action !="" && Domain !=""){fetchData();}
}, [Action,Domain,version]);

useEffect(() => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
Expand All @@ -68,15 +103,40 @@ export const MockRequestSection = () => {
}
};

const handleAction = (event:
| React.MouseEvent<Element>
| React.KeyboardEvent<Element>
| React.FocusEvent<Element>
| null,
value: {} | null) => {
console.log("action", event);
setAction(value as string); // Ensure value is a string and set the version
};

const handledomain = (event:
| React.MouseEvent<Element>
| React.KeyboardEvent<Element>
| React.FocusEvent<Element>
| null,
value: {} | null) => {
console.log("action", event);
setDomain(value as string); // Ensure value is a string and set the version
};

const handleLogChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
console.log("insidelog",e.target.value)
setLog(e.target.value);
detectAction(e.target.value, version);
};

const handleclick = () => {
setshow(!show);
};

const handleSubmit = async () => {
let url = `${
VITE_SERVER_URL
}/${domain.toLowerCase()}/${Object.keys(URL_MAPPING).filter((key) =>
let url = `${VITE_SERVER_URL}/${domain.toLowerCase()}/${Object.keys(
URL_MAPPING
).filter((key) =>
URL_MAPPING[key as keyof typeof URL_MAPPING].includes(action as string)
)}/${action}?mode=mock&version=${version}`;
if (activeScenario?.scenario)
Expand Down Expand Up @@ -116,6 +176,59 @@ export const MockRequestSection = () => {
>
<Stack spacing={2} justifyContent="center" alignItems="center">
<Typography variant="h5">Mock Server</Typography>
<Stack style={{ width: "100%" ,display:"flex",flexDirection:"row"}}>
{show && (<>
<Select
sx={{
height: "10%",
width: "22%",
marginLeft: "auto",
position: "relative",
left:"30%"
}}
placeholder="Select Domain"
value={Domain}
onChange={handledomain}
>
{ALL_SUB_DOMAINS[domain as keyof typeof ALL_SUB_DOMAINS].map((action, index) => (
<Option value={action} key={action + index}>
{action.split(":").pop()}
</Option>
))}
</Select>
<Select
sx={{
height: "10%",
width: "20%",
marginLeft: "auto",
position: "relative",
left:"15%"
}}
placeholder="Select Action"
value={Action}
onChange={handleAction}
>
{All_Actions.map((action, index) => (
<Option value={action} key={action + index}>
{action}
</Option>
))}
</Select></>
)}

<Fab
color="primary"
size="small"
style={{
// backgroundColor: "red",
marginLeft: "auto",
}}
onClick={handleclick}
aria-label="add"
>
<AddIcon />
</Fab>
</Stack>
{domain === "retail" && (
<Select
placeholder="Select a version"
Expand Down Expand Up @@ -144,7 +257,7 @@ export const MockRequestSection = () => {
</Stack>
)}
</FormControl>
{action && (
{action && (
<Grid container>
<Grid item xs={12} md={6}>
<Box
Expand Down Expand Up @@ -204,9 +317,9 @@ export const MockRequestSection = () => {
variant="solid"
onClick={handleSubmit}
disabled={
logError ||
!action ||
(scenarios!.length > 0 && !activeScenario)
logError|| !Action
// !action ||
// (scenarios!.length > 0 && !activeScenario) ?? false
}
>
Submit
Expand Down
29 changes: 28 additions & 1 deletion apps/frontend/src/utils/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -593,4 +593,31 @@ export const SWAGGER_DOMAIN_FIELDS = {
type: "select",
domainDepended: false,
options: ALL_DOMAINS,
};
};
export const All_Actions=[
"Search","on_Search","Select","on_Select","Init","on_Init","Confirm","on_Confirm","Status","on_Status","Update","on_Update","Cancel","on_Cancel"
]

export const ALL_SUB_DOMAINS={
retail:["ONDC:RET1A",
"ONDC:RET1B",
"ONDC:RET1C",
"ONDC:RET1D",
"ONDC:RET10",
"ONDC:RET12",
"ONDC:RET13",
"ONDC:RET14",
"ONDC:RET10",
"ONDC:RET12"],
agri:["ONDC:AGR10",
"ONDC:AGR11"],
logistics:["ONDC:LOG10",
"ONDC:LOG11"],
subscription:["ONDC:MEC10"],
services:["ONDC:SRV11",
"ONDC:SRV13",
"ONDC:SRV14",
"ONDC:SRV16",
"ONDC:SRV17",
"ONDC:SRV18",]
}
3 changes: 2 additions & 1 deletion apps/frontend/src/utils/hooks/useAction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,9 +69,10 @@ export const useAction = () => {
} else {
setScenarios([]);
}

console.log("scenarios",scenarios)
setLogError(false);
} catch (error) {
console.log("errror",error)
setLogError(true);
setAction(undefined);
}
Expand Down
Loading