Refactor frontend API use (#477)

 feat(App.tsx): add getVersion function to retrieve app version from
API
The fetch call to retrieve the app version has been replaced with a call
to the getVersion function. This function retrieves the app version from
the API. This change improves the code's readability and reduces the
amount of code needed to retrieve the app version.

🐛 fix(GenericNode/index.tsx): replace fetch call with postValidateNode
function call to validate node
 feat(GenericNode/index.tsx): add postValidateNode function to validate
node via API
The fetch call to validate the node has been replaced with a call to the
postValidateNode function. This function validates the node via the API.
This change improves the code's readability and reduces the amount of
code needed to validate the node.

🐛 fix(codeAreaModal/index.tsx): replace checkCode function call with
postValidateCode function call to validate code
 feat(codeAreaModal/index.tsx): add postValidateCode function to
validate code via API
The checkCode function call to validate the code has been replaced with
a call to the postValidateCode function. This function validates the
code via the API. This change improves the code's readability and
reduces the amount of code needed to validate the code.
This commit is contained in:
anovazzi1 2023-06-12 16:37:08 -03:00 committed by GitHub
commit 5857253e71
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
10 changed files with 64 additions and 41 deletions

View file

@ -14,6 +14,7 @@ import TabsManagerComponent from "./pages/FlowPage/components/tabsManagerCompone
import { ErrorBoundary } from "react-error-boundary";
import CrashErrorComponent from "./components/CrashErrorComponent";
import { TabsContext } from "./contexts/tabsContext";
import { getVersion } from "./controllers/API";
export default function App() {
let { setCurrent, setShowSideBar, setIsStackedOpen } =
@ -49,11 +50,9 @@ export default function App() {
// Initialize state variable for the version
const [version, setVersion] = useState("");
useEffect(() => {
fetch("/version")
.then((res) => res.json())
.then((data) => {
setVersion(data.version);
});
getVersion().then((response) => {
setVersion(response.data.version);
});
}, []);
// Use effect hook to update alertsList when a new alert is added
useEffect(() => {

View file

@ -33,6 +33,7 @@ import { NodeToolbar } from "reactflow";
import NodeToolbarComponent from "../../pages/FlowPage/components/nodeToolbarComponent";
import ShadTooltip from "../../components/ShadTooltipComponent";
import { postValidateNode } from "../../controllers/API";
export default function GenericNode({
data,
selected,
@ -62,17 +63,13 @@ export default function GenericNode({
const validateNode = useCallback(
debounce(async () => {
try {
const response = await fetch(`/validate/node/${data.id}`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(reactFlowInstance.toObject()),
});
const response = await postValidateNode(
data.id,
reactFlowInstance.toObject()
);
if (response.status === 200) {
let jsonResponse = await response.json();
let jsonResponseParsed = await JSON.parse(jsonResponse);
let jsonResponseParsed = await JSON.parse(response.data);
setValidationStatus(jsonResponseParsed);
}
} catch (error) {
@ -148,11 +145,10 @@ export default function GenericNode({
"Validating..."
) : (
<div className="max-h-96 overflow-auto">
{validationStatus.params
.split("\n")
.map((line, index) => (
<div key={index}>{line}</div>
))}
{validationStatus.params ||
""
.split("\n")
.map((line, index) => <div key={index}>{line}</div>)}
</div>
)
}

View file

@ -34,7 +34,7 @@ export default function IntComponent({
if (disableCopyPaste) setDisableCopyPaste(false);
}}
onKeyDown={(event) => {
console.log(event);
// console.log(event);
if (
event.key !== "Backspace" &&
event.key !== "Enter" &&

View file

@ -69,12 +69,12 @@ export function TabsProvider({ children }: { children: ReactNode }) {
Saveflows.forEach((flow) => {
if (flow.data && flow.data?.nodes)
flow.data?.nodes.forEach((node) => {
console.log(node.data.type);
// console.log(node.data.type);
//looking for file fields to prevent saving the content and breaking the flow for exceeding the the data limite for local storage
Object.keys(node.data.node.template).forEach((key) => {
console.log(node.data.node.template[key].type);
// console.log(node.data.node.template[key].type);
if (node.data.node.template[key].type === "file") {
console.log(node.data.node.template[key]);
// console.log(node.data.node.template[key]);
node.data.node.template[key].content = null;
node.data.node.template[key].value = "";
}
@ -139,7 +139,7 @@ export function TabsProvider({ children }: { children: ReactNode }) {
useEffect(() => {
//save tabs locally
console.log(id);
// console.log(id);
save();
}, [flows, id, tabIndex, newNodeId]);

View file

@ -3,24 +3,52 @@ import { APIObjectType, sendAllProps } from "../../types/api/index";
import axios, { AxiosResponse } from "axios";
import { FlowType } from "../../types/flow";
// when serving with static files
// We need to add /api/v1/ to the url in the axios calls
/**
* Retrieves all data from the API.
* @returns {Promise<AxiosResponse<APIObjectType>>} A promise that resolves to an AxiosResponse object containing the API data.
*/
export async function getAll(): Promise<AxiosResponse<APIObjectType>> {
return await axios.get(`/all`);
return await axios.get(`/api/v1/all`);
}
export async function sendAll(data: sendAllProps) {
return await axios.post(`/predict`, data);
return await axios.post(`/api/v1/predict`, data);
}
export async function checkCode(
export async function postValidateCode(
code: string
): Promise<AxiosResponse<errorsTypeAPI>> {
return await axios.post("/validate/code", { code });
return await axios.post("/api/v1/validate/code", { code });
}
export async function postValidateNode(
nodeId: string,
data: any
): Promise<AxiosResponse<string>> {
return await axios.post(`/api/v1/validate/node/${nodeId}`, { data });
}
export async function checkPrompt(
template: string
): Promise<AxiosResponse<PromptTypeAPI>> {
return await axios.post("/validate/prompt", { template });
return await axios.post("/api/v1/validate/prompt", { template });
}
/**
* Retrieves the version of the API.
* @returns {Promise<AxiosResponse<{ version: string }>>} A promise that resolves to an AxiosResponse object containing the API version.
* @example
* const response = await getVersion();
* console.log(response.data.version);
* // 0.1.0
*/
export async function getVersion(): Promise<
AxiosResponse<{ version: string }>
> {
return await axios.get("/api/v1/version");
}
export async function getExamples(): Promise<FlowType[]> {

View file

@ -87,7 +87,7 @@ export default function EditNodeModal({ data }: { data: NodeDataType }) {
setNodeValue(!nodeValue);
}
console.log(data.node.template);
// console.log(data.node.template);
return (
<Dialog open={true} onOpenChange={setModalOpen}>

View file

@ -8,7 +8,7 @@ import "ace-builds/src-noconflict/theme-twilight";
import "ace-builds/src-noconflict/ext-language_tools";
// import "ace-builds/webpack-resolver";
import { darkContext } from "../../contexts/darkContext";
import { checkCode } from "../../controllers/API";
import { postValidateCode } from "../../controllers/API";
import { alertContext } from "../../contexts/alertContext";
import { TabsContext } from "../../contexts/tabsContext";
import {
@ -81,7 +81,7 @@ export default function CodeAreaModal({
<Button
className="mt-3"
onClick={() => {
checkCode(code)
postValidateCode(code)
.then((apiReturn) => {
if (apiReturn.data) {
let importsErrors = apiReturn.data.imports.errors;

View file

@ -61,7 +61,7 @@ const NodeToolbarComponent = (props) => {
)}
onClick={(event) => {
event.preventDefault();
console.log(reactFlowInstance.getNode(props.data.id));
// console.log(reactFlowInstance.getNode(props.data.id));
paste(
{
nodes: [reactFlowInstance.getNode(props.data.id)],
@ -94,7 +94,7 @@ const NodeToolbarComponent = (props) => {
</ShadTooltip>
)}
{/*
{/*
<Menu as="div" className="relative inline-block text-left z-100">
<button className="hover:dark:hover:bg-[#242f47] text-gray-700 transition-all duration-500 ease-in-out dark:bg-gray-800 dark:text-gray-300 shadow-md relative -ml-px inline-flex items-center bg-white px-2 py-2 ring-1 ring-inset ring-gray-300 hover:bg-gray-50 focus:z-10 rounded-r-md">
<div>

View file

@ -68,7 +68,7 @@ export default function FlowPage({ flow }: { flow: FlowType }) {
!disableCopyPaste
) {
event.preventDefault();
console.log(_.cloneDeep(lastSelection));
// console.log(_.cloneDeep(lastSelection));
setLastCopiedSelection(_.cloneDeep(lastSelection));
}
if (

View file

@ -2,11 +2,11 @@ import { defineConfig } from "vite";
import react from "@vitejs/plugin-react-swc";
import svgr from "vite-plugin-svgr";
const apiRoutes = [
"/all",
"/predict",
"^/validate/*",
"^/chat/*",
"/version",
"/api/v1/all",
"/api/v1/predict",
"^/api/v1/validate/*",
"/api/v1/chat/*",
"/api/v1/version",
"/health",
];
@ -19,7 +19,7 @@ const proxyTargets = apiRoutes.reduce((proxyObj, route) => {
changeOrigin: true,
secure: false,
ws: true,
rewrite: (path) => `/api/v1${path}`,
// rewrite: (path) => `/api/v1${path}`,
};
return proxyObj;
}, {});