forked from aep-dev/aep-explorer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcustom_method.tsx
More file actions
163 lines (146 loc) · 6.28 KB
/
Copy pathcustom_method.tsx
File metadata and controls
163 lines (146 loc) · 6.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
import { useState, useMemo } from "react";
import { CustomMethod } from "@aep_dev/aep-lib-ts";
import { ResourceInstance, mockAwareFetch } from "@/state/fetch";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Field, FieldGroup, FieldLabel, FieldError } from "@/components/ui/field";
import { Form as FormProvider, FormField } from "@/components/ui/form";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { toast } from "@/hooks/use-toast";
import { createValidationSchemaFromRawSchema } from "@/lib/utils";
type CustomMethodProps = {
resourceInstance: ResourceInstance;
customMethod: CustomMethod;
};
export function CustomMethodComponent(props: CustomMethodProps) {
const [response, setResponse] = useState<any>(null);
const [isLoading, setIsLoading] = useState(false);
const validationSchema = useMemo(() => {
return createValidationSchemaFromRawSchema(props.customMethod.request);
}, [props.customMethod]);
const form = useForm({
resolver: zodResolver(validationSchema),
defaultValues: {}
});
const onSubmit = async (data: Record<string, unknown>) => {
setIsLoading(true);
setResponse(null);
try {
// Construct the URL for the custom method
const url = `${props.resourceInstance.schema.server_url}/${props.resourceInstance.path}:${props.customMethod.name}`;
const response = await mockAwareFetch(url, {
method: props.customMethod.method,
headers: {
'Content-Type': 'application/json',
},
body: Object.keys(data).length > 0 ? JSON.stringify(data) : undefined,
});
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
const responseData = await response.json();
setResponse(responseData);
toast({ description: `${props.customMethod.name} completed successfully` });
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
toast({ description: `Failed to execute ${props.customMethod.name}: ${message}` });
setResponse({ error: message });
} finally {
setIsLoading(false);
}
};
const getInputType = (propertyType: string) => {
switch (propertyType) {
case 'integer':
case 'number':
return 'number';
case 'boolean':
return 'checkbox';
default:
return 'text';
}
};
const renderField = (name: string, propSchema: any, parentPath: string = ''): React.ReactNode => {
const fieldPath = parentPath ? `${parentPath}.${name}` : name;
if (propSchema.type === 'object') {
const nestedProperties = propSchema.properties || {};
return (
<div key={fieldPath} className="space-y-2 pl-4 border-l-2 border-gray-200">
<label className="font-medium">{name}</label>
{Object.entries(nestedProperties).map(([nestedName, nestedSchema]) =>
renderField(nestedName, nestedSchema, fieldPath)
)}
</div>
);
}
return (
<FormField
key={fieldPath}
control={form.control}
name={fieldPath}
render={({ field, fieldState }) => {
const inputId = `input-${fieldPath}`;
return (
<Field data-invalid={!!fieldState.error}>
<FieldLabel htmlFor={inputId}>{name}</FieldLabel>
<Input
{...field}
id={inputId}
type={getInputType(propSchema.type)}
checked={propSchema.type === 'boolean' ? field.value : undefined}
onChange={propSchema.type === 'boolean'
? (e) => field.onChange(e.target.checked)
: field.onChange
}
aria-invalid={!!fieldState.error}
/>
{fieldState.error && (
<FieldError>{fieldState.error.message}</FieldError>
)}
</Field>
);
}}
/>
);
};
const formFields = useMemo(() => {
if (!props.customMethod.request || !props.customMethod.request.properties) {
return null;
}
const properties = props.customMethod.request.properties;
return Object.entries(properties).map(([name, schema]) =>
renderField(name, schema)
);
}, [props.customMethod, form.control]);
return (
<Card>
<CardHeader>
<CardTitle>{props.customMethod.name}</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<FormProvider {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
{formFields && (
<FieldGroup>
{formFields}
</FieldGroup>
)}
<Button type="submit" disabled={isLoading}>
{isLoading ? 'Submitting...' : 'Submit'}
</Button>
</form>
</FormProvider>
{response && (
<div className="mt-4 p-4 bg-gray-50 dark:bg-gray-800 rounded-md">
<h4 className="font-medium mb-2">Response:</h4>
<pre className="text-sm overflow-auto">
{JSON.stringify(response, null, 2)}
</pre>
</div>
)}
</CardContent>
</Card>
);
}