import JSONEditor from 'components/common/JSONEditor/JSONEditor'; import PageLoader from 'components/common/PageLoader/PageLoader'; import { CreateTopicMessage, Partition, TopicMessageSchema, } from 'generated-sources'; import React from 'react'; import { useForm, Controller } from 'react-hook-form'; import { useHistory } from 'react-router'; import { clusterTopicMessagesPath } from 'lib/paths'; import jsf from 'json-schema-faker'; import validateMessage from './validateMessage'; export interface Props { clusterName: string; topicName: string; fetchTopicMessageSchema: (clusterName: string, topicName: string) => void; sendTopicMessage: ( clusterName: string, topicName: string, payload: CreateTopicMessage ) => void; messageSchema: TopicMessageSchema | undefined; schemaIsFetched: boolean; messageIsSending: boolean; partitions: Partition[]; } const SendMessage: React.FC = ({ clusterName, topicName, fetchTopicMessageSchema, sendTopicMessage, messageSchema, schemaIsFetched, messageIsSending, partitions, }) => { const [keyExampleValue, setKeyExampleValue] = React.useState(''); const [contentExampleValue, setContentExampleValue] = React.useState(''); const [schemaIsReady, setSchemaIsReady] = React.useState(false); const [schemaErrors, setSchemaErrors] = React.useState([]); const { register, handleSubmit, formState: { isSubmitting, isDirty }, control, } = useForm({ mode: 'onChange' }); const history = useHistory(); jsf.option('fillProperties', false); jsf.option('alwaysFakeOptionals', true); React.useEffect(() => { fetchTopicMessageSchema(clusterName, topicName); }, []); React.useEffect(() => { if (schemaIsFetched && messageSchema) { setKeyExampleValue( JSON.stringify( jsf.generate(JSON.parse(messageSchema.key.schema)), null, '\t' ) ); setContentExampleValue( JSON.stringify( jsf.generate(JSON.parse(messageSchema.value.schema)), null, '\t' ) ); setSchemaIsReady(true); } }, [schemaIsFetched]); const onSubmit = async (data: { key: string; content: string; headers: string; partition: number; }) => { if (messageSchema) { const key = data.key || keyExampleValue; const content = data.content || contentExampleValue; const { partition } = data; const headers = data.headers ? JSON.parse(data.headers) : undefined; const messageIsValid = await validateMessage( key, content, messageSchema, setSchemaErrors ); if (messageIsValid) { sendTopicMessage(clusterName, topicName, { key, content, headers, partition, }); history.push(clusterTopicMessagesPath(clusterName, topicName)); } } }; if (!schemaIsReady) { return ; } return (
( )} />
( )} />
( )} />
{schemaErrors && (
{schemaErrors.map((err) => (

{err}

))}
)}
); }; export default SendMessage;