feat: Implement getData query and send a message action for slack

This commit is contained in:
Faruk AYDIN
2022-03-15 02:57:37 +03:00
committed by Ömer Faruk Aydın
parent f8c7b85682
commit 8512528fcf
14 changed files with 305 additions and 92 deletions

View File

@@ -0,0 +1,10 @@
import ListChannels from './data/list-channels';
import { IJSONObject } from '@automatisch/types';
export default class Data {
listChannels: ListChannels;
constructor(connectionData: IJSONObject) {
this.listChannels = new ListChannels(connectionData);
}
}

View File

@@ -0,0 +1,21 @@
import type { IJSONObject } from '@automatisch/types';
import { WebClient } from '@slack/web-api';
export default class ListChannels {
client: WebClient;
constructor(connectionData: IJSONObject) {
this.client = new WebClient(connectionData.accessToken as string);
}
async run() {
const { channels } = await this.client.conversations.list();
return channels.map((channel) => {
return {
value: channel.id,
name: channel.name,
};
});
}
}

View File

@@ -1,4 +1,5 @@
import Authentication from './authentication'; import Authentication from './authentication';
import Data from './data';
import { import {
IService, IService,
IAuthentication, IAuthentication,
@@ -8,8 +9,10 @@ import {
export default class Slack implements IService { export default class Slack implements IService {
authenticationClient: IAuthentication; authenticationClient: IAuthentication;
data: Data;
constructor(appData: IApp, connectionData: IJSONObject) { constructor(appData: IApp, connectionData: IJSONObject) {
this.authenticationClient = new Authentication(appData, connectionData); this.authenticationClient = new Authentication(appData, connectionData);
this.data = new Data(connectionData);
} }
} }

View File

@@ -96,5 +96,58 @@
} }
] ]
} }
],
"actions": [
{
"name": "Send a message to channel",
"key": "sendMessageToChannel",
"description": "Send a message to a specific channel you specify.",
"substeps": [
{
"key": "chooseAccount",
"name": "Choose account"
},
{
"key": "setupAction",
"name": "Set up action",
"arguments": [
{
"label": "Channel",
"key": "channel",
"type": "dropdown",
"required": true,
"description": "Pick a channel to send the message to.",
"variables": false,
"source": {
"type": "query",
"name": "getData",
"arguments": [
{
"name": "stepId",
"value": "{step.id}"
},
{
"name": "key",
"value": "listChannels"
}
]
}
},
{
"label": "Message text",
"key": "message",
"type": "string",
"required": true,
"description": "The content of your new message.",
"variables": true
}
]
},
{
"key": "testStep",
"name": "Test action"
}
]
}
] ]
} }

View File

@@ -221,7 +221,7 @@
"key": "myTweet", "key": "myTweet",
"interval": "15m", "interval": "15m",
"description": "Will be triggered when you tweet something new.", "description": "Will be triggered when you tweet something new.",
"subSteps": [ "substeps": [
{ {
"key": "chooseAccount", "key": "chooseAccount",
"name": "Choose account" "name": "Choose account"
@@ -236,7 +236,7 @@
"name": "User Tweet", "name": "User Tweet",
"key": "userTweet", "key": "userTweet",
"description": "Will be triggered when a specific user tweet something new.", "description": "Will be triggered when a specific user tweet something new.",
"subSteps": [ "substeps": [
{ {
"key": "chooseAccount", "key": "chooseAccount",
"name": "Choose account" "name": "Choose account"
@@ -263,7 +263,7 @@
"name": "Search Tweet", "name": "Search Tweet",
"key": "searchTweet", "key": "searchTweet",
"description": "Will be triggered when any user tweet something containing a specific keyword, phrase, username or hashtag.", "description": "Will be triggered when any user tweet something containing a specific keyword, phrase, username or hashtag.",
"subSteps": [ "substeps": [
{ {
"key": "chooseAccount", "key": "chooseAccount",
"name": "Choose account" "name": "Choose account"
@@ -292,7 +292,7 @@
"name": "Create Tweet", "name": "Create Tweet",
"key": "createTweet", "key": "createTweet",
"description": "Will create a tweet.", "description": "Will create a tweet.",
"subSteps": [ "substeps": [
{ {
"key": "chooseAccount", "key": "chooseAccount",
"name": "Choose account" "name": "Choose account"

View File

@@ -0,0 +1,31 @@
import App from '../../models/app';
import Connection from '../../models/connection';
import Step from '../../models/step';
import { IApp } from '@automatisch/types';
import Context from '../../types/express/context';
import ListData from '../../apps/slack/data/list-channels';
type Params = {
stepId: string;
key: string;
};
const getData = async (_parent: unknown, params: Params, context: Context) => {
const step = await context.currentUser
.$relatedQuery('steps')
.withGraphFetched('connection')
.findById(params.stepId);
const connection = step.connection;
const appData = App.findOneByKey(step.appKey);
const AppClass = (await import(`../../apps/${step.appKey}`)).default;
const appInstance = new AppClass(appData, connection.formattedData);
const command = appInstance.data[params.key];
const fetchedData = await command.run();
return fetchedData;
};
export default getData;

View File

@@ -8,6 +8,7 @@ import getFlows from './queries/get-flows';
import getStepWithTestExecutions from './queries/get-step-with-test-executions'; import getStepWithTestExecutions from './queries/get-step-with-test-executions';
import getExecutions from './queries/get-executions'; import getExecutions from './queries/get-executions';
import getExecutionSteps from './queries/get-execution-steps'; import getExecutionSteps from './queries/get-execution-steps';
import getData from './queries/get-data';
const queryResolvers = { const queryResolvers = {
getApps, getApps,
@@ -20,6 +21,7 @@ const queryResolvers = {
getStepWithTestExecutions, getStepWithTestExecutions,
getExecutions, getExecutions,
getExecutionSteps, getExecutionSteps,
getData,
}; };
export default queryResolvers; export default queryResolvers;

View File

@@ -13,6 +13,7 @@ type Query {
limit: Int! limit: Int!
offset: Int! offset: Int!
): ExecutionStepConnection ): ExecutionStepConnection
getData(stepId: String!, key: String!): JSONObject
} }
type Mutation { type Mutation {
@@ -48,22 +49,34 @@ type Action {
name: String name: String
key: String key: String
description: String description: String
subSteps: [ActionSubStep] substeps: [ActionSubstep]
} }
type ActionSubStep { type ActionSubstep {
key: String key: String
name: String name: String
arguments: [ActionSubStepArgument] arguments: [ActionSubstepArgument]
} }
type ActionSubStepArgument { type ActionSubstepArgument {
label: String label: String
key: String key: String
type: String type: String
description: String description: String
required: Boolean required: Boolean
variables: Boolean variables: Boolean
source: ActionSubstepArgumentSource
}
type ActionSubstepArgumentSource {
type: String
name: String
arguments: [ActionSubstepArgumentSourceArgument]
}
type ActionSubstepArgumentSourceArgument {
name: String
value: String
} }
type App { type App {
@@ -337,16 +350,16 @@ type Trigger {
name: String name: String
key: String key: String
description: String description: String
subSteps: [TriggerSubStep] substeps: [TriggerSubstep]
} }
type TriggerSubStep { type TriggerSubstep {
key: String key: String
name: String name: String
arguments: [TriggerSubStepArgument] arguments: [TriggerSubstepArgument]
} }
type TriggerSubStepArgument { type TriggerSubstepArgument {
label: String label: String
key: String key: String
type: String type: String

View File

@@ -9,6 +9,7 @@ class ExecutionStep extends Base {
dataIn!: Record<string, unknown>; dataIn!: Record<string, unknown>;
dataOut!: Record<string, unknown>; dataOut!: Record<string, unknown>;
status: string; status: string;
step: Step;
static tableName = 'execution_steps'; static tableName = 'execution_steps';

View File

@@ -78,6 +78,16 @@ class Processor {
fetchedActionData = await command.run(); fetchedActionData = await command.run();
} }
console.log(
'previous execution step dataOut :',
previousExecutionStep?.dataOut
);
console.log(
'previous execution step parameters :',
previousExecutionStep?.step.parameters
);
previousExecutionStep = await execution previousExecutionStep = await execution
.$relatedQuery('executionSteps') .$relatedQuery('executionSteps')
.insertAndFetch({ .insertAndFetch({

View File

@@ -70,7 +70,30 @@ export interface IUser {
steps: IStep[]; steps: IStep[];
} }
export interface IField { export interface IFieldDropdown {
key: string;
label: string;
type: 'dropdown';
required: boolean;
readOnly: boolean;
value: string;
placeholder: string | null;
description: string;
docUrl: string;
clickToCopy: boolean;
name: string;
variables: boolean;
source: {
type: string;
name: string;
arguments: {
name: string;
value: string;
}[];
};
}
export interface IFieldText {
key: string; key: string;
label: string; label: string;
type: string; type: string;
@@ -85,6 +108,8 @@ export interface IField {
variables: boolean; variables: boolean;
} }
type IField = IFieldDropdown | IFieldText;
export interface IAuthenticationStepField { export interface IAuthenticationStepField {
name: string; name: string;
value: string | null; value: string | null;

View File

@@ -23,7 +23,13 @@ import AppIcon from 'components/AppIcon';
import { GET_APPS } from 'graphql/queries/get-apps'; import { GET_APPS } from 'graphql/queries/get-apps';
import { GET_STEP_WITH_TEST_EXECUTIONS } from 'graphql/queries/get-step-with-test-executions'; import { GET_STEP_WITH_TEST_EXECUTIONS } from 'graphql/queries/get-step-with-test-executions';
import useFormatMessage from 'hooks/useFormatMessage'; import useFormatMessage from 'hooks/useFormatMessage';
import { AppIconWrapper, AppIconStatusIconWrapper, Content, Header, Wrapper } from './style'; import {
AppIconWrapper,
AppIconStatusIconWrapper,
Content,
Header,
Wrapper,
} from './style';
type FlowStepProps = { type FlowStepProps = {
collapsed?: boolean; collapsed?: boolean;
@@ -32,26 +38,29 @@ type FlowStepProps = {
onOpen?: () => void; onOpen?: () => void;
onClose?: () => void; onClose?: () => void;
onChange: (step: IStep) => void; onChange: (step: IStep) => void;
} };
const validIcon = <CheckCircleIcon color="success" />; const validIcon = <CheckCircleIcon color="success" />;
const errorIcon = <ErrorIcon color="error" />; const errorIcon = <ErrorIcon color="error" />;
export default function FlowStep(props: FlowStepProps): React.ReactElement | null { export default function FlowStep(
props: FlowStepProps
): React.ReactElement | null {
const { collapsed, index, onChange } = props; const { collapsed, index, onChange } = props;
const contextButtonRef = React.useRef<HTMLButtonElement | null>(null); const contextButtonRef = React.useRef<HTMLButtonElement | null>(null);
const step: IStep = props.step; const step: IStep = props.step;
const [anchorEl, setAnchorEl] = React.useState<HTMLButtonElement | null>(null); const [anchorEl, setAnchorEl] = React.useState<HTMLButtonElement | null>(
null
);
const isTrigger = step.type === 'trigger'; const isTrigger = step.type === 'trigger';
const formatMessage = useFormatMessage(); const formatMessage = useFormatMessage();
const [currentSubstep, setCurrentSubstep] = React.useState<number | null>(2); const [currentSubstep, setCurrentSubstep] = React.useState<number | null>(2);
const { data } = useQuery(GET_APPS, { variables: { onlyWithTriggers: isTrigger }}); const { data } = useQuery(GET_APPS, {
variables: { onlyWithTriggers: isTrigger },
});
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',
}); });
@@ -64,17 +73,27 @@ export default function FlowStep(props: FlowStepProps): React.ReactElement | nul
}, },
}); });
} }
}, [collapsed, stepWithTestExecutionsCalled, getStepWithTestExecutions, step.id, isTrigger]); }, [
collapsed,
stepWithTestExecutionsCalled,
getStepWithTestExecutions,
step.id,
isTrigger,
]);
const apps: IApp[] = data?.getApps; const apps: IApp[] = data?.getApps;
const app = apps?.find((currentApp: IApp) => currentApp.key === step.appKey); const app = apps?.find((currentApp: IApp) => currentApp.key === step.appKey);
const actionsOrTriggers = isTrigger ? app?.triggers : app?.actions; const actionsOrTriggers = isTrigger ? app?.triggers : app?.actions;
const substeps = React.useMemo(() => actionsOrTriggers?.find(({ key }) => key === step.key)?.subSteps || [], [actionsOrTriggers, step?.key]); const substeps = React.useMemo(
() =>
actionsOrTriggers?.find(({ key }) => key === step.key)?.substeps || [],
[actionsOrTriggers, step?.key]
);
const handleChange = React.useCallback(({ step }: { step: IStep }) => { const handleChange = React.useCallback(({ step }: { step: IStep }) => {
onChange(step); onChange(step);
}, []) }, []);
const expandNextStep = React.useCallback(() => { const expandNextStep = React.useCallback(() => {
setCurrentSubstep((currentSubstep) => (currentSubstep ?? 0) + 1); setCurrentSubstep((currentSubstep) => (currentSubstep ?? 0) + 1);
@@ -82,24 +101,28 @@ export default function FlowStep(props: FlowStepProps): React.ReactElement | nul
const handleSubmit = (val: any) => { const handleSubmit = (val: any) => {
handleChange({ step: val as IStep }); handleChange({ step: val as IStep });
} };
if (!apps) return null; if (!apps) return null;
const onContextMenuClose = (event: React.SyntheticEvent) => { const onContextMenuClose = (event: React.SyntheticEvent) => {
event.stopPropagation(); event.stopPropagation();
setAnchorEl(null); setAnchorEl(null);
} };
const onContextMenuClick = (event: React.SyntheticEvent) => { const onContextMenuClick = (event: React.SyntheticEvent) => {
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: number) => setCurrentSubstep((value) => value !== substepIndex ? substepIndex : null); const toggleSubstep = (substepIndex: number) =>
setCurrentSubstep((value) =>
value !== substepIndex ? substepIndex : null
);
const validationStatusIcon = step.status === 'completed' ? validIcon : errorIcon; const validationStatusIcon =
step.status === 'completed' ? validIcon : errorIcon;
return ( return (
<Wrapper elevation={collapsed ? 1 : 4} onClick={onOpen}> <Wrapper elevation={collapsed ? 1 : 4} onClick={onOpen}>
@@ -115,11 +138,9 @@ export default function FlowStep(props: FlowStepProps): React.ReactElement | nul
<div> <div>
<Typography variant="caption"> <Typography variant="caption">
{ {isTrigger
isTrigger ? ? formatMessage('flowStep.triggerType')
formatMessage('flowStep.triggerType') : : formatMessage('flowStep.actionType')}
formatMessage('flowStep.actionType')
}
</Typography> </Typography>
<Typography variant="body2"> <Typography variant="body2">
@@ -129,9 +150,15 @@ export default function FlowStep(props: FlowStepProps): React.ReactElement | nul
<Box display="flex" flex={1} justifyContent="end"> <Box display="flex" flex={1} justifyContent="end">
{/* as there are no other actions besides "delete step", we hide the context menu. */} {/* as there are no other actions besides "delete step", we hide the context menu. */}
{!isTrigger && <IconButton color="primary" onClick={onContextMenuClick} ref={contextButtonRef}> {!isTrigger && (
<MoreHorizIcon /> <IconButton
</IconButton>} color="primary"
onClick={onContextMenuClick}
ref={contextButtonRef}
>
<MoreHorizIcon />
</IconButton>
)}
</Box> </Box>
</Stack> </Stack>
</Header> </Header>
@@ -139,7 +166,11 @@ export default function FlowStep(props: FlowStepProps): React.ReactElement | nul
<Collapse in={!collapsed} unmountOnExit> <Collapse in={!collapsed} unmountOnExit>
<Content> <Content>
<List> <List>
<StepExecutionsProvider value={stepWithTestExecutionsData?.getStepWithTestExecutions as IStep[]}> <StepExecutionsProvider
value={
stepWithTestExecutionsData?.getStepWithTestExecutions as IStep[]
}
>
<Form defaultValues={step} onSubmit={handleSubmit}> <Form defaultValues={step} onSubmit={handleSubmit}>
<ChooseAppAndEventSubstep <ChooseAppAndEventSubstep
expanded={currentSubstep === 0} expanded={currentSubstep === 0}
@@ -151,45 +182,56 @@ export default function FlowStep(props: FlowStepProps): React.ReactElement | nul
step={step} step={step}
/> />
{substeps?.length > 0 && substeps.map((substep: { name: string, key: string, arguments: IField[] }, index: number) => ( {substeps?.length > 0 &&
<React.Fragment key={`${substep?.name}-${index}`}> substeps.map(
{substep.key === 'chooseAccount' && ( (
<ChooseAccountSubstep substep: {
expanded={currentSubstep === (index + 1)} name: string;
substep={substep} key: string;
onExpand={() => toggleSubstep((index + 1))} arguments: IField[];
onCollapse={() => toggleSubstep((index + 1))} },
onSubmit={expandNextStep} index: number
onChange={handleChange} ) => (
step={step} <React.Fragment key={`${substep?.name}-${index}`}>
/> {substep.key === 'chooseAccount' && (
)} <ChooseAccountSubstep
expanded={currentSubstep === index + 1}
substep={substep}
onExpand={() => toggleSubstep(index + 1)}
onCollapse={() => toggleSubstep(index + 1)}
onSubmit={expandNextStep}
onChange={handleChange}
step={step}
/>
)}
{substep.key === 'testStep' && ( {substep.key === 'testStep' && (
<TestSubstep <TestSubstep
expanded={currentSubstep === (index + 1)} expanded={currentSubstep === index + 1}
substep={substep} substep={substep}
onExpand={() => toggleSubstep((index + 1))} onExpand={() => toggleSubstep(index + 1)}
onCollapse={() => toggleSubstep((index + 1))} onCollapse={() => toggleSubstep(index + 1)}
onSubmit={expandNextStep} onSubmit={expandNextStep}
onChange={handleChange} onChange={handleChange}
step={step} step={step}
/> />
)} )}
{['chooseAccount', 'testStep'].includes(substep.key) === false && ( {['chooseAccount', 'testStep'].includes(substep.key) ===
<FlowSubstep false && (
expanded={currentSubstep === (index + 1)} <FlowSubstep
substep={substep} expanded={currentSubstep === index + 1}
onExpand={() => toggleSubstep((index + 1))} substep={substep}
onCollapse={() => toggleSubstep((index + 1))} onExpand={() => toggleSubstep(index + 1)}
onSubmit={expandNextStep} onCollapse={() => toggleSubstep(index + 1)}
onChange={handleChange} onSubmit={expandNextStep}
step={step} onChange={handleChange}
/> step={step}
)} />
</React.Fragment> )}
))} </React.Fragment>
)
)}
</Form> </Form>
</StepExecutionsProvider> </StepExecutionsProvider>
</List> </List>
@@ -200,12 +242,14 @@ export default function FlowStep(props: FlowStepProps): React.ReactElement | nul
</Button> </Button>
</Collapse> </Collapse>
{anchorEl && <FlowStepContextMenu {anchorEl && (
stepId={step.id} <FlowStepContextMenu
deletable={!isTrigger} stepId={step.id}
onClose={onContextMenuClose} deletable={!isTrigger}
anchorEl={anchorEl} onClose={onContextMenuClose}
/>} anchorEl={anchorEl}
/>
)}
</Wrapper> </Wrapper>
) );
}; }

View File

@@ -2,7 +2,7 @@ import { gql } from '@apollo/client';
export const GET_APP = gql` export const GET_APP = gql`
query GetApp($key: AvailableAppsEnumType!) { query GetApp($key: AvailableAppsEnumType!) {
getApp (key: $key) { getApp(key: $key) {
name name
key key
iconUrl iconUrl
@@ -54,7 +54,7 @@ export const GET_APP = gql`
name name
key key
description description
subSteps { substeps {
name name
} }
} }
@@ -62,7 +62,7 @@ export const GET_APP = gql`
name name
key key
description description
subSteps { substeps {
name name
} }
} }

View File

@@ -53,7 +53,7 @@ export const GET_APPS = gql`
name name
key key
description description
subSteps { substeps {
key key
name name
arguments { arguments {
@@ -68,7 +68,7 @@ export const GET_APPS = gql`
name name
key key
description description
subSteps { substeps {
key key
name name
arguments { arguments {
@@ -83,4 +83,4 @@ export const GET_APPS = gql`
} }
} }
} }
`; `;