refactor: rewrite useApps with RQ

This commit is contained in:
Rıdvan Akca
2024-03-04 17:25:49 +03:00
parent 1870aead73
commit e5670d820d
5 changed files with 76 additions and 21 deletions

View File

@@ -4,11 +4,11 @@ import { renderObject } from '../../../../helpers/renderer.js';
export default async (request, response) => { export default async (request, response) => {
let apps = await App.findAll(request.query.name); let apps = await App.findAll(request.query.name);
if (request.query.onlyWithTriggers) { if (request.query.onlyWithTriggers === 'true') {
apps = apps.filter((app) => app.triggers?.length); apps = apps.filter((app) => app.triggers?.length);
} }
if (request.query.onlyWithActions) { if (request.query.onlyWithActions === 'true') {
apps = apps.filter((app) => app.actions?.length); apps = apps.filter((app) => app.actions?.length);
} }

View File

@@ -8,6 +8,7 @@ import ListItem from '@mui/material/ListItem';
import TextField from '@mui/material/TextField'; import TextField from '@mui/material/TextField';
import Autocomplete from '@mui/material/Autocomplete'; import Autocomplete from '@mui/material/Autocomplete';
import Chip from '@mui/material/Chip'; import Chip from '@mui/material/Chip';
import useFormatMessage from 'hooks/useFormatMessage'; import useFormatMessage from 'hooks/useFormatMessage';
import useApps from 'hooks/useApps'; import useApps from 'hooks/useApps';
import { EditorContext } from 'contexts/Editor'; import { EditorContext } from 'contexts/Editor';
@@ -18,13 +19,16 @@ const optionGenerator = (app) => ({
label: app.name, label: app.name,
value: app.key, value: app.key,
}); });
const eventOptionGenerator = (app) => ({ const eventOptionGenerator = (app) => ({
label: app.name, label: app.name,
value: app.key, value: app.key,
type: app?.type, type: app?.type,
}); });
const getOption = (options, selectedOptionValue) => const getOption = (options, selectedOptionValue) =>
options.find((option) => option.value === selectedOptionValue); options.find((option) => option.value === selectedOptionValue);
function ChooseAppAndEventSubstep(props) { function ChooseAppAndEventSubstep(props) {
const { const {
substep, substep,
@@ -39,26 +43,36 @@ function ChooseAppAndEventSubstep(props) {
const editorContext = React.useContext(EditorContext); const editorContext = React.useContext(EditorContext);
const isTrigger = step.type === 'trigger'; const isTrigger = step.type === 'trigger';
const isAction = step.type === 'action'; const isAction = step.type === 'action';
const { apps } = useApps({
const { data: apps } = useApps({
onlyWithTriggers: isTrigger, onlyWithTriggers: isTrigger,
onlyWithActions: isAction, onlyWithActions: isAction,
}); });
const app = apps?.find((currentApp) => currentApp.key === step.appKey);
const app = apps?.data?.find((currentApp) => currentApp.key === step.appKey);
const appOptions = React.useMemo( const appOptions = React.useMemo(
() => apps?.map((app) => optionGenerator(app)) || [], () => apps?.data?.map((app) => optionGenerator(app)) || [],
[apps], [apps?.data],
); );
const actionsOrTriggers = (isTrigger ? app?.triggers : app?.actions) || []; const actionsOrTriggers = (isTrigger ? app?.triggers : app?.actions) || [];
const actionOrTriggerOptions = React.useMemo( const actionOrTriggerOptions = React.useMemo(
() => actionsOrTriggers.map((trigger) => eventOptionGenerator(trigger)), () => actionsOrTriggers.map((trigger) => eventOptionGenerator(trigger)),
[app?.key], [app?.key],
); );
const selectedActionOrTrigger = actionsOrTriggers.find( const selectedActionOrTrigger = actionsOrTriggers.find(
(actionOrTrigger) => actionOrTrigger.key === step?.key, (actionOrTrigger) => actionOrTrigger.key === step?.key,
); );
const isWebhook = isTrigger && selectedActionOrTrigger?.type === 'webhook'; const isWebhook = isTrigger && selectedActionOrTrigger?.type === 'webhook';
const { name } = substep; const { name } = substep;
const valid = !!step.key && !!step.appKey; const valid = !!step.key && !!step.appKey;
// placeholders // placeholders
const onEventChange = React.useCallback( const onEventChange = React.useCallback(
(event, selectedOption) => { (event, selectedOption) => {
@@ -79,6 +93,7 @@ function ChooseAppAndEventSubstep(props) {
}, },
[step, onChange], [step, onChange],
); );
const onAppChange = React.useCallback( const onAppChange = React.useCallback(
(event, selectedOption) => { (event, selectedOption) => {
if (typeof selectedOption === 'object') { if (typeof selectedOption === 'object') {
@@ -100,7 +115,9 @@ function ChooseAppAndEventSubstep(props) {
}, },
[step, onChange], [step, onChange],
); );
const onToggle = expanded ? onCollapse : onExpand; const onToggle = expanded ? onCollapse : onExpand;
return ( return (
<React.Fragment> <React.Fragment>
<FlowSubstepTitle <FlowSubstepTitle

View File

@@ -9,6 +9,7 @@ import Tab from '@mui/material/Tab';
import Typography from '@mui/material/Typography'; import Typography from '@mui/material/Typography';
import Tooltip from '@mui/material/Tooltip'; import Tooltip from '@mui/material/Tooltip';
import Box from '@mui/material/Box'; import Box from '@mui/material/Box';
import TabPanel from 'components/TabPanel'; import TabPanel from 'components/TabPanel';
import SearchableJSONViewer from 'components/SearchableJSONViewer'; import SearchableJSONViewer from 'components/SearchableJSONViewer';
import AppIcon from 'components/AppIcon'; import AppIcon from 'components/AppIcon';
@@ -26,11 +27,13 @@ import { ExecutionStepPropType, StepPropType } from 'propTypes/propTypes';
function ExecutionStepId(props) { function ExecutionStepId(props) {
const formatMessage = useFormatMessage(); const formatMessage = useFormatMessage();
const id = ( const id = (
<Typography variant="caption" component="span"> <Typography variant="caption" component="span">
{props.id} {props.id}
</Typography> </Typography>
); );
return ( return (
<Box sx={{ display: 'flex' }} gridArea="id"> <Box sx={{ display: 'flex' }} gridArea="id">
<Typography variant="caption" fontWeight="bold"> <Typography variant="caption" fontWeight="bold">
@@ -48,6 +51,7 @@ function ExecutionStepDate(props) {
const formatMessage = useFormatMessage(); const formatMessage = useFormatMessage();
const createdAt = DateTime.fromMillis(parseInt(props.createdAt, 10)); const createdAt = DateTime.fromMillis(parseInt(props.createdAt, 10));
const relativeCreatedAt = createdAt.toRelative(); const relativeCreatedAt = createdAt.toRelative();
return ( return (
<Tooltip <Tooltip
title={createdAt.toLocaleString(DateTime.DATETIME_FULL_WITH_SECONDS)} title={createdAt.toLocaleString(DateTime.DATETIME_FULL_WITH_SECONDS)}
@@ -75,15 +79,21 @@ function ExecutionStep(props) {
const isTrigger = step.type === 'trigger'; const isTrigger = step.type === 'trigger';
const isAction = step.type === 'action'; const isAction = step.type === 'action';
const formatMessage = useFormatMessage(); const formatMessage = useFormatMessage();
const { apps } = useApps({
const { data: apps } = useApps({
onlyWithTriggers: isTrigger, onlyWithTriggers: isTrigger,
onlyWithActions: isAction, onlyWithActions: isAction,
}); });
const app = apps?.find((currentApp) => currentApp.key === step.appKey);
if (!apps) return null; const app = apps?.data?.find((currentApp) => currentApp.key === step.appKey);
if (!apps?.data) return null;
const validationStatusIcon = const validationStatusIcon =
executionStep.status === 'success' ? validIcon : errorIcon; executionStep.status === 'success' ? validIcon : errorIcon;
const hasError = !!executionStep.errorDetails; const hasError = !!executionStep.errorDetails;
return ( return (
<Wrapper elevation={1} data-test="execution-step"> <Wrapper elevation={1} data-test="execution-step">
<Header> <Header>

View File

@@ -14,6 +14,7 @@ import CircularProgress from '@mui/material/CircularProgress';
import CheckCircleIcon from '@mui/icons-material/CheckCircle'; import CheckCircleIcon from '@mui/icons-material/CheckCircle';
import { yupResolver } from '@hookform/resolvers/yup'; import { yupResolver } from '@hookform/resolvers/yup';
import * as yup from 'yup'; import * as yup from 'yup';
import { EditorContext } from 'contexts/Editor'; import { EditorContext } from 'contexts/Editor';
import { StepExecutionsProvider } from 'contexts/StepExecutions'; import { StepExecutionsProvider } from 'contexts/StepExecutions';
import TestSubstep from 'components/TestSubstep'; import TestSubstep from 'components/TestSubstep';
@@ -83,6 +84,7 @@ function generateValidationSchema(substeps) {
} }
} }
} }
return { return {
...allValidations, ...allValidations,
...substepArgumentValidations, ...substepArgumentValidations,
@@ -90,9 +92,11 @@ function generateValidationSchema(substeps) {
}, },
{}, {},
); );
const validationSchema = yup.object({ const validationSchema = yup.object({
parameters: yup.object(fieldValidations), parameters: yup.object(fieldValidations),
}); });
return yupResolver(validationSchema); return yupResolver(validationSchema);
} }
@@ -106,16 +110,19 @@ function FlowStep(props) {
const isAction = step.type === 'action'; const isAction = step.type === 'action';
const formatMessage = useFormatMessage(); const formatMessage = useFormatMessage();
const [currentSubstep, setCurrentSubstep] = React.useState(0); const [currentSubstep, setCurrentSubstep] = React.useState(0);
const { apps } = useApps({
const { data: apps } = useApps({
onlyWithTriggers: isTrigger, onlyWithTriggers: isTrigger,
onlyWithActions: isAction, onlyWithActions: isAction,
}); });
const [ const [
getStepWithTestExecutions, getStepWithTestExecutions,
{ data: stepWithTestExecutionsData, called: stepWithTestExecutionsCalled }, { data: stepWithTestExecutionsData, called: stepWithTestExecutionsCalled },
] = useLazyQuery(GET_STEP_WITH_TEST_EXECUTIONS, { ] = useLazyQuery(GET_STEP_WITH_TEST_EXECUTIONS, {
fetchPolicy: 'network-only', fetchPolicy: 'network-only',
}); });
React.useEffect(() => { React.useEffect(() => {
if (!stepWithTestExecutionsCalled && !collapsed && !isTrigger) { if (!stepWithTestExecutionsCalled && !collapsed && !isTrigger) {
getStepWithTestExecutions({ getStepWithTestExecutions({
@@ -131,26 +138,33 @@ function FlowStep(props) {
step.id, step.id,
isTrigger, isTrigger,
]); ]);
const app = apps?.find((currentApp) => currentApp.key === step.appKey);
const app = apps?.data?.find((currentApp) => currentApp.key === step.appKey);
const actionsOrTriggers = (isTrigger ? app?.triggers : app?.actions) || []; const actionsOrTriggers = (isTrigger ? app?.triggers : app?.actions) || [];
const actionOrTrigger = actionsOrTriggers?.find( const actionOrTrigger = actionsOrTriggers?.find(
({ key }) => key === step.key, ({ key }) => key === step.key,
); );
const substeps = actionOrTrigger?.substeps || []; const substeps = actionOrTrigger?.substeps || [];
const handleChange = React.useCallback(({ step }) => { const handleChange = React.useCallback(({ step }) => {
onChange(step); onChange(step);
}, []); }, []);
const expandNextStep = React.useCallback(() => { const expandNextStep = React.useCallback(() => {
setCurrentSubstep((currentSubstep) => (currentSubstep ?? 0) + 1); setCurrentSubstep((currentSubstep) => (currentSubstep ?? 0) + 1);
}, []); }, []);
const handleSubmit = (val) => { const handleSubmit = (val) => {
handleChange({ step: val }); handleChange({ step: val });
}; };
const stepValidationSchema = React.useMemo( const stepValidationSchema = React.useMemo(
() => generateValidationSchema(substeps), () => generateValidationSchema(substeps),
[substeps], [substeps],
); );
if (!apps) {
if (!apps?.data) {
return ( return (
<CircularProgress <CircularProgress
data-test="step-circular-loader" data-test="step-circular-loader"
@@ -158,22 +172,29 @@ function FlowStep(props) {
/> />
); );
} }
const onContextMenuClose = (event) => { const onContextMenuClose = (event) => {
event.stopPropagation(); event.stopPropagation();
setAnchorEl(null); setAnchorEl(null);
}; };
const onContextMenuClick = (event) => { const onContextMenuClick = (event) => {
event.stopPropagation(); event.stopPropagation();
setAnchorEl(contextButtonRef.current); setAnchorEl(contextButtonRef.current);
}; };
const onOpen = () => collapsed && props.onOpen?.(); const onOpen = () => collapsed && props.onOpen?.();
const onClose = () => props.onClose?.(); const onClose = () => props.onClose?.();
const toggleSubstep = (substepIndex) => const toggleSubstep = (substepIndex) =>
setCurrentSubstep((value) => setCurrentSubstep((value) =>
value !== substepIndex ? substepIndex : null, value !== substepIndex ? substepIndex : null,
); );
const validationStatusIcon = const validationStatusIcon =
step.status === 'completed' ? validIcon : errorIcon; step.status === 'completed' ? validIcon : errorIcon;
return ( return (
<Wrapper <Wrapper
elevation={collapsed ? 1 : 4} elevation={collapsed ? 1 : 4}

View File

@@ -1,12 +1,19 @@
import { useQuery } from '@apollo/client'; import { useQuery } from '@tanstack/react-query';
import { GET_APPS } from 'graphql/queries/get-apps';
import api from 'helpers/api';
export default function useApps(variables) { export default function useApps(variables) {
const { data, loading } = useQuery(GET_APPS, { const query = useQuery({
variables, queryKey: ['apps', variables],
queryFn: async ({ payload, signal }) => {
const { data } = await api.get('/v1/apps', {
params: variables,
signal,
});
return data;
},
}); });
const apps = data?.getApps;
return { return query;
apps,
loading,
};
} }