Merge pull request #2066 from automatisch/aut-1240

feat: write and implement REST API endpoint to create step
This commit is contained in:
Ali BARIN
2024-09-10 14:31:12 +02:00
committed by GitHub
14 changed files with 295 additions and 130 deletions

View File

@@ -0,0 +1,14 @@
import { renderObject } from '../../../../helpers/renderer.js';
export default async (request, response) => {
const flow = await request.currentUser.authorizedFlows
.clone()
.findById(request.params.flowId)
.throwIfNotFound();
const createdActionStep = await flow.createActionStep(
request.body.previousStepId
);
renderObject(response, createdActionStep, { status: 201 });
};

View File

@@ -0,0 +1,176 @@
import Crypto from 'node:crypto';
import { describe, it, expect, beforeEach } from 'vitest';
import request from 'supertest';
import app from '../../../../app.js';
import createAuthTokenByUserId from '../../../../helpers/create-auth-token-by-user-id.js';
import { createUser } from '../../../../../test/factories/user.js';
import { createFlow } from '../../../../../test/factories/flow.js';
import { createStep } from '../../../../../test/factories/step.js';
import createStepMock from '../../../../../test/mocks/rest/api/v1/flows/create-step.js';
import { createPermission } from '../../../../../test/factories/permission.js';
describe('POST /api/v1/flows/:flowId/steps', () => {
let currentUser, flow, triggerStep, token;
beforeEach(async () => {
currentUser = await createUser();
flow = await createFlow({ userId: currentUser.id });
triggerStep = await createStep({ flowId: flow.id, type: 'trigger' });
await createStep({ flowId: flow.id, type: 'action' });
token = await createAuthTokenByUserId(currentUser.id);
});
it('should return created step for current user', async () => {
await createPermission({
roleId: currentUser.roleId,
subject: 'Flow',
action: 'read',
conditions: ['isCreator'],
});
await createPermission({
roleId: currentUser.roleId,
subject: 'Flow',
action: 'update',
conditions: ['isCreator'],
});
const response = await request(app)
.post(`/api/v1/flows/${flow.id}/steps`)
.set('Authorization', token)
.send({
previousStepId: triggerStep.id,
})
.expect(201);
const expectedPayload = await createStepMock({
id: response.body.data.id,
position: 2,
});
expect(response.body).toMatchObject(expectedPayload);
});
it('should return created step for another user', async () => {
const anotherUser = await createUser();
const anotherUserFlow = await createFlow({ userId: anotherUser.id });
const anotherUserFlowTriggerStep = await createStep({
flowId: anotherUserFlow.id,
type: 'trigger',
});
await createStep({ flowId: anotherUserFlow.id, type: 'action' });
await createPermission({
roleId: currentUser.roleId,
subject: 'Flow',
action: 'read',
conditions: [],
});
await createPermission({
roleId: currentUser.roleId,
subject: 'Flow',
action: 'update',
conditions: [],
});
const response = await request(app)
.post(`/api/v1/flows/${anotherUserFlow.id}/steps`)
.set('Authorization', token)
.send({
previousStepId: anotherUserFlowTriggerStep.id,
})
.expect(201);
const expectedPayload = await createStepMock({
id: response.body.data.id,
position: 2,
});
expect(response.body).toMatchObject(expectedPayload);
});
it('should return bad request response for invalid flow UUID', async () => {
await createPermission({
roleId: currentUser.roleId,
subject: 'Flow',
action: 'read',
conditions: ['isCreator'],
});
await createPermission({
roleId: currentUser.roleId,
subject: 'Flow',
action: 'update',
conditions: ['isCreator'],
});
await request(app)
.post('/api/v1/flows/invalidFlowUUID/steps')
.set('Authorization', token)
.send({
previousStepId: triggerStep.id,
})
.expect(400);
});
it('should return not found response for invalid flow UUID', async () => {
await createPermission({
roleId: currentUser.roleId,
subject: 'Flow',
action: 'read',
conditions: ['isCreator'],
});
await createPermission({
roleId: currentUser.roleId,
subject: 'Flow',
action: 'update',
conditions: ['isCreator'],
});
const notExistingFlowUUID = Crypto.randomUUID();
await request(app)
.post(`/api/v1/flows/${notExistingFlowUUID}/steps`)
.set('Authorization', token)
.send({
previousStepId: triggerStep.id,
})
.expect(404);
});
it('should return not found response for invalid flow UUID', async () => {
await createPermission({
roleId: currentUser.roleId,
subject: 'Flow',
action: 'read',
conditions: ['isCreator'],
});
await createPermission({
roleId: currentUser.roleId,
subject: 'Flow',
action: 'update',
conditions: ['isCreator'],
});
const notExistingStepUUID = Crypto.randomUUID();
await request(app)
.post(`/api/v1/flows/${flow.id}/steps`)
.set('Authorization', token)
.send({
previousStepId: notExistingStepUUID,
})
.expect(404);
});
});

View File

@@ -1,5 +1,4 @@
import createConnection from './mutations/create-connection.js';
import createStep from './mutations/create-step.js';
import createUser from './mutations/create-user.ee.js';
import deleteFlow from './mutations/delete-flow.js';
import deleteRole from './mutations/delete-role.ee.js';
@@ -23,7 +22,6 @@ import deleteCurrentUser from './mutations/delete-current-user.ee.js';
const mutationResolvers = {
createConnection,
createFlow,
createStep,
createUser,
deleteCurrentUser,
deleteFlow,

View File

@@ -1,56 +0,0 @@
import App from '../../models/app.js';
import Flow from '../../models/flow.js';
const createStep = async (_parent, params, context) => {
const conditions = context.currentUser.can('update', 'Flow');
const userFlows = context.currentUser.$relatedQuery('flows');
const allFlows = Flow.query();
const flowsQuery = conditions.isCreator ? userFlows : allFlows;
const { input } = params;
if (input.appKey && input.key) {
await App.checkAppAndAction(input.appKey, input.key);
}
if (input.appKey && !input.key) {
await App.findOneByKey(input.appKey);
}
const flow = await flowsQuery
.findOne({
id: input.flow.id,
})
.throwIfNotFound();
const previousStep = await flow
.$relatedQuery('steps')
.findOne({
id: input.previousStep.id,
})
.throwIfNotFound();
const step = await flow.$relatedQuery('steps').insertAndFetch({
key: input.key,
appKey: input.appKey,
type: 'action',
position: previousStep.position + 1,
});
const nextSteps = await flow
.$relatedQuery('steps')
.where('position', '>=', step.position)
.whereNot('id', step.id);
const nextStepQueries = nextSteps.map(async (nextStep, index) => {
await nextStep.$query().patchAndFetch({
position: step.position + index + 1,
});
});
await Promise.all(nextStepQueries);
return step;
};
export default createStep;

View File

@@ -4,7 +4,6 @@ type Query {
type Mutation {
createConnection(input: CreateConnectionInput): Connection
createFlow(input: CreateFlowInput): Flow
createStep(input: CreateStepInput): Step
createUser(input: CreateUserInput): UserWithAcceptInvitationUrl
deleteCurrentUser: Boolean
deleteFlow(input: DeleteFlowInput): Boolean
@@ -266,17 +265,6 @@ input DuplicateFlowInput {
id: String!
}
input CreateStepInput {
id: String
previousStepId: String
key: String
appKey: String
connection: StepConnectionInput
flow: StepFlowInput
parameters: JSONObject
previousStep: PreviousStepInput
}
input UpdateStepInput {
id: String
previousStepId: String

View File

@@ -93,6 +93,10 @@ const authorizationList = {
action: 'update',
subject: 'Flow',
},
'POST /api/v1/flows/:flowId/steps': {
action: 'update',
subject: 'Flow',
},
};
export const authorizeUser = async (request, response, next) => {

View File

@@ -135,6 +135,31 @@ class Flow extends Base {
return this.$query().withGraphFetched('steps');
}
async createActionStep(previousStepId) {
const previousStep = await this.$relatedQuery('steps')
.findById(previousStepId)
.throwIfNotFound();
const createdStep = await this.$relatedQuery('steps').insertAndFetch({
type: 'action',
position: previousStep.position + 1,
});
const nextSteps = await this.$relatedQuery('steps')
.where('position', '>=', createdStep.position)
.whereNot('id', createdStep.id);
const nextStepQueries = nextSteps.map(async (nextStep, index) => {
return await nextStep.$query().patchAndFetch({
position: createdStep.position + index + 1,
});
});
await Promise.all(nextStepQueries);
return createdStep;
}
async $beforeUpdate(opt, queryContext) {
await super.$beforeUpdate(opt, queryContext);

View File

@@ -82,6 +82,8 @@ class Step extends Base {
});
get webhookUrl() {
if (!this.webhookPath) return null;
return new URL(this.webhookPath, appConfig.webhookUrl).toString();
}

View File

@@ -5,6 +5,7 @@ import getFlowsAction from '../../../controllers/api/v1/flows/get-flows.js';
import getFlowAction from '../../../controllers/api/v1/flows/get-flow.js';
import updateFlowAction from '../../../controllers/api/v1/flows/update-flow.js';
import createFlowAction from '../../../controllers/api/v1/flows/create-flow.js';
import createStepAction from '../../../controllers/api/v1/flows/create-step.js';
const router = Router();
@@ -12,5 +13,11 @@ router.get('/', authenticateUser, authorizeUser, getFlowsAction);
router.get('/:flowId', authenticateUser, authorizeUser, getFlowAction);
router.post('/', authenticateUser, authorizeUser, createFlowAction);
router.patch('/:flowId', authenticateUser, authorizeUser, updateFlowAction);
router.post(
'/:flowId/steps',
authenticateUser,
authorizeUser,
createStepAction
);
export default router;

View File

@@ -0,0 +1,26 @@
const createStepMock = async (step) => {
const data = {
id: step.id,
type: step.type || 'action',
key: step.key || null,
appKey: step.appKey || null,
iconUrl: step.iconUrl || null,
webhookUrl: step.webhookUrl || null,
status: step.status || 'incomplete',
position: step.position,
parameters: step.parameters || {},
};
return {
data,
meta: {
type: 'Step',
count: 1,
isArray: false,
currentPage: null,
totalPages: null,
},
};
};
export default createStepMock;

View File

@@ -4,7 +4,7 @@ import Box from '@mui/material/Box';
import IconButton from '@mui/material/IconButton';
import AddIcon from '@mui/icons-material/Add';
import { CREATE_STEP } from 'graphql/mutations/create-step';
import useCreateStep from 'hooks/useCreateStep';
import { UPDATE_STEP } from 'graphql/mutations/update-step';
import FlowStep from 'components/FlowStep';
import { FlowPropType } from 'propTypes/propTypes';
@@ -12,9 +12,9 @@ import { useQueryClient } from '@tanstack/react-query';
function Editor(props) {
const [updateStep] = useMutation(UPDATE_STEP);
const [createStep, { loading: creationInProgress }] =
useMutation(CREATE_STEP);
const { flow } = props;
const { mutateAsync: createStep, isPending: isCreateStepPending } =
useCreateStep(flow?.id);
const [triggerStep] = flow.steps;
const [currentStepId, setCurrentStepId] = React.useState(triggerStep.id);
const queryClient = useQueryClient();
@@ -48,24 +48,13 @@ function Editor(props) {
const addStep = React.useCallback(
async (previousStepId) => {
const mutationInput = {
previousStep: {
id: previousStepId,
},
flow: {
id: flow.id,
},
};
const createdStep = await createStep({
variables: { input: mutationInput },
const { data: createdStep } = await createStep({
previousStepId,
});
const createdStepId = createdStep.data.createStep.id;
setCurrentStepId(createdStepId);
await queryClient.invalidateQueries({ queryKey: ['flows', flow.id] });
setCurrentStepId(createdStep.id);
},
[createStep, flow.id, queryClient],
[createStep],
);
const openNextStep = React.useCallback((nextStep) => {
@@ -101,7 +90,7 @@ function Editor(props) {
<IconButton
onClick={() => addStep(step.id)}
color="primary"
disabled={creationInProgress || flow.active}
disabled={isCreateStepPending || flow.active}
>
<AddIcon />
</IconButton>

View File

@@ -4,8 +4,9 @@ import { useQueryClient } from '@tanstack/react-query';
import { FlowPropType } from 'propTypes/propTypes';
import ReactFlow, { useNodesState, useEdgesState } from 'reactflow';
import 'reactflow/dist/style.css';
import { UPDATE_STEP } from 'graphql/mutations/update-step';
import { CREATE_STEP } from 'graphql/mutations/create-step';
import useCreateStep from 'hooks/useCreateStep';
import { useAutoLayout } from './useAutoLayout';
import { useScrollBoundaries } from './useScrollBoundaries';
@@ -36,8 +37,9 @@ const edgeTypes = {
const EditorNew = ({ flow }) => {
const [updateStep] = useMutation(UPDATE_STEP);
const queryClient = useQueryClient();
const [createStep, { loading: stepCreationInProgress }] =
useMutation(CREATE_STEP);
const { mutateAsync: createStep, isPending: isCreateStepPending } =
useCreateStep(flow?.id);
const [nodes, setNodes, onNodesChange] = useNodesState(
generateInitialNodes(flow),
@@ -111,26 +113,11 @@ const EditorNew = ({ flow }) => {
const onAddStep = useCallback(
async (previousStepId) => {
const mutationInput = {
previousStep: {
id: previousStepId,
},
flow: {
id: flow.id,
},
};
const { data: createdStep } = await createStep({ previousStepId });
const {
data: { createStep: createdStep },
} = await createStep({
variables: { input: mutationInput },
});
const createdStepId = createdStep.id;
await queryClient.invalidateQueries({ queryKey: ['flows', flow.id] });
createdStepIdRef.current = createdStepId;
createdStepIdRef.current = createdStep.id;
},
[flow.id, createStep, queryClient],
[createStep],
);
useEffect(() => {
@@ -260,7 +247,7 @@ const EditorNew = ({ flow }) => {
>
<EdgesContext.Provider
value={{
stepCreationInProgress,
stepCreationInProgress: isCreateStepPending,
onAddStep,
flowActive: flow.active,
}}

View File

@@ -1,19 +0,0 @@
import { gql } from '@apollo/client';
export const CREATE_STEP = gql`
mutation CreateStep($input: CreateStepInput) {
createStep(input: $input) {
id
type
key
appKey
parameters
iconUrl
position
webhookUrl
status
connection {
id
}
}
}
`;

View File

@@ -0,0 +1,24 @@
import { useMutation, useQueryClient } from '@tanstack/react-query';
import api from 'helpers/api';
export default function useCreateStep(flowId) {
const queryClient = useQueryClient();
const query = useMutation({
mutationFn: async ({ previousStepId }) => {
const { data } = await api.post(`/v1/flows/${flowId}/steps`, {
previousStepId,
});
return data;
},
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: ['flows', flowId],
});
},
});
return query;
}