Merge pull request #2083 from automatisch/aut-1257

feat: write and implement REST API endpoint to update step
This commit is contained in:
Ömer Faruk Aydın
2024-09-19 13:40:57 +03:00
committed by GitHub
13 changed files with 342 additions and 129 deletions

View File

@@ -0,0 +1,22 @@
import { renderObject } from '../../../../helpers/renderer.js';
export default async (request, response) => {
let step = await request.currentUser.authorizedSteps
.findById(request.params.stepId)
.throwIfNotFound();
step = await step.updateFor(request.currentUser, stepParams(request));
renderObject(response, step);
};
const stepParams = (request) => {
const { connectionId, appKey, key, parameters } = request.body;
return {
connectionId,
appKey,
key,
parameters,
};
};

View File

@@ -0,0 +1,211 @@
import { describe, it, beforeEach, expect } from 'vitest';
import request from 'supertest';
import Crypto from 'crypto';
import app from '../../../../app.js';
import createAuthTokenByUserId from '../../../../helpers/create-auth-token-by-user-id.js';
import { createUser } from '../../../../../test/factories/user.js';
import { createConnection } from '../../../../../test/factories/connection.js';
import { createFlow } from '../../../../../test/factories/flow.js';
import { createStep } from '../../../../../test/factories/step.js';
import { createPermission } from '../../../../../test/factories/permission.js';
import updateStepMock from '../../../../../test/mocks/rest/api/v1/steps/update-step.js';
describe('PATCH /api/v1/steps/:stepId', () => {
let currentUser, token;
beforeEach(async () => {
currentUser = await createUser();
token = await createAuthTokenByUserId(currentUser.id);
});
it('should update the step of the current user', async () => {
const currentUserFlow = await createFlow({ userId: currentUser.id });
const currentUserConnection = await createConnection({
key: 'deepl',
});
await createStep({
flowId: currentUserFlow.id,
connectionId: currentUserConnection.id,
});
const actionStep = await createStep({
flowId: currentUserFlow.id,
connectionId: currentUserConnection.id,
appKey: 'deepl',
key: 'translateText',
});
await createPermission({
action: 'read',
subject: 'Flow',
roleId: currentUser.roleId,
conditions: ['isCreator'],
});
await createPermission({
action: 'update',
subject: 'Flow',
roleId: currentUser.roleId,
conditions: ['isCreator'],
});
const response = await request(app)
.patch(`/api/v1/steps/${actionStep.id}`)
.set('Authorization', token)
.send({
parameters: {
text: 'Hello world!',
targetLanguage: 'de',
},
})
.expect(200);
const refetchedStep = await actionStep.$query();
const expectedResponse = updateStepMock(refetchedStep);
expect(response.body).toStrictEqual(expectedResponse);
});
it('should update the step of the another user', async () => {
const anotherUser = await createUser();
const anotherUserFlow = await createFlow({ userId: anotherUser.id });
const anotherUserConnection = await createConnection({
key: 'deepl',
});
await createStep({
flowId: anotherUserFlow.id,
connectionId: anotherUserConnection.id,
});
const actionStep = await createStep({
flowId: anotherUserFlow.id,
connectionId: anotherUserConnection.id,
});
await createPermission({
action: 'read',
subject: 'Flow',
roleId: currentUser.roleId,
conditions: [],
});
await createPermission({
action: 'update',
subject: 'Flow',
roleId: currentUser.roleId,
conditions: [],
});
const response = await request(app)
.patch(`/api/v1/steps/${actionStep.id}`)
.set('Authorization', token)
.send({
parameters: {
text: 'Hello world!',
targetLanguage: 'de',
},
})
.expect(200);
const refetchedStep = await actionStep.$query();
const expectedResponse = updateStepMock(refetchedStep);
expect(response.body).toStrictEqual(expectedResponse);
});
it('should return not found response for inaccessible connection', async () => {
const currentUserFlow = await createFlow({ userId: currentUser.id });
const anotherUser = await createUser();
const anotherUserConnection = await createConnection({
key: 'deepl',
userId: anotherUser.id,
});
await createStep({
flowId: currentUserFlow.id,
});
const actionStep = await createStep({
flowId: currentUserFlow.id,
});
await createPermission({
action: 'read',
subject: 'Flow',
roleId: currentUser.roleId,
conditions: ['isCreator'],
});
await createPermission({
action: 'update',
subject: 'Flow',
roleId: currentUser.roleId,
conditions: ['isCreator'],
});
await createPermission({
action: 'read',
subject: 'Connection',
roleId: currentUser.roleId,
conditions: ['isCreator'],
});
await request(app)
.patch(`/api/v1/steps/${actionStep.id}`)
.set('Authorization', token)
.send({
connectionId: anotherUserConnection.id,
})
.expect(404);
});
it('should return not found response for not existing step UUID', async () => {
await createPermission({
action: 'update',
subject: 'Flow',
roleId: currentUser.roleId,
conditions: [],
});
await createPermission({
action: 'read',
subject: 'Flow',
roleId: currentUser.roleId,
conditions: [],
});
const notExistingStepUUID = Crypto.randomUUID();
await request(app)
.patch(`/api/v1/steps/${notExistingStepUUID}`)
.set('Authorization', token)
.expect(404);
});
it('should return bad request response for invalid step UUID', async () => {
await createPermission({
action: 'update',
subject: 'Flow',
roleId: currentUser.roleId,
conditions: [],
});
await createPermission({
action: 'read',
subject: 'Flow',
roleId: currentUser.roleId,
conditions: [],
});
await request(app)
.patch('/api/v1/steps/invalidStepUUID')
.set('Authorization', token)
.expect(400);
});
});

View File

@@ -1,5 +1,3 @@
import updateStep from './mutations/update-step.js';
// Converted mutations
import executeFlow from './mutations/execute-flow.js';
import updateUser from './mutations/update-user.ee.js';
@@ -21,7 +19,6 @@ const mutationResolvers = {
updateConnection,
updateCurrentUser,
updateFlowStatus,
updateStep,
updateUser,
verifyConnection,
};

View File

@@ -1,68 +0,0 @@
import App from '../../models/app.js';
import Step from '../../models/step.js';
import Connection from '../../models/connection.js';
const updateStep = async (_parent, params, context) => {
const { isCreator } = context.currentUser.can('update', 'Flow');
const userSteps = context.currentUser.$relatedQuery('steps');
const allSteps = Step.query();
const baseQuery = isCreator ? userSteps : allSteps;
const { input } = params;
let step = await baseQuery
.findOne({
'steps.id': input.id,
flow_id: input.flow.id,
})
.throwIfNotFound();
if (input.connection.id) {
let canSeeAllConnections = false;
try {
const conditions = context.currentUser.can('read', 'Connection');
canSeeAllConnections = !conditions.isCreator;
} catch {
// void
}
const userConnections = context.currentUser.$relatedQuery('connections');
const allConnections = Connection.query();
const baseConnectionsQuery = canSeeAllConnections
? allConnections
: userConnections;
const connection = await baseConnectionsQuery
.clone()
.findById(input.connection?.id);
if (!connection) {
throw new Error('The connection does not exist!');
}
}
if (step.isTrigger) {
await App.checkAppAndTrigger(input.appKey, input.key);
}
if (step.isAction) {
await App.checkAppAndAction(input.appKey, input.key);
}
step = await Step.query()
.patchAndFetchById(input.id, {
key: input.key,
appKey: input.appKey,
connectionId: input.connection.id,
parameters: input.parameters,
status: 'incomplete'
})
.withGraphFetched('connection');
await step.updateWebhookUrl();
return step;
};
export default updateStep;

View File

@@ -10,7 +10,6 @@ type Mutation {
updateConnection(input: UpdateConnectionInput): Connection
updateCurrentUser(input: UpdateCurrentUserInput): User
updateFlowStatus(input: UpdateFlowStatusInput): Flow
updateStep(input: UpdateStepInput): Step
updateUser(input: UpdateUserInput): User
verifyConnection(input: VerifyConnectionInput): Connection
}
@@ -245,17 +244,6 @@ input ExecuteFlowInput {
stepId: String!
}
input UpdateStepInput {
id: String
previousStepId: String
key: String
appKey: String
connection: StepConnectionInput
flow: StepFlowInput
parameters: JSONObject
previousStep: PreviousStepInput
}
input CreateUserInput {
fullName: String!
email: String!

View File

@@ -37,6 +37,10 @@ const authorizationList = {
action: 'read',
subject: 'Flow',
},
'PATCH /api/v1/steps/:stepId': {
action: 'update',
subject: 'Flow',
},
'POST /api/v1/steps/:stepId/test': {
action: 'update',
subject: 'Flow',

View File

@@ -334,6 +334,39 @@ class Step extends Base {
await Promise.all(nextStepQueries);
}
async updateFor(user, newStepData) {
const { connectionId, appKey, key, parameters } = newStepData;
if (connectionId && (appKey || this.appKey)) {
await user.authorizedConnections
.findOne({
id: connectionId,
key: appKey || this.appKey,
})
.throwIfNotFound();
}
if (this.isTrigger && appKey && key) {
await App.checkAppAndTrigger(appKey, key);
}
if (this.isAction && appKey && key) {
await App.checkAppAndAction(appKey, key);
}
const updatedStep = await this.$query().patchAndFetch({
key: key,
appKey: appKey,
connectionId: connectionId,
parameters: parameters,
status: 'incomplete',
});
await updatedStep.updateWebhookUrl();
return updatedStep;
}
}
export default Step;

View File

@@ -7,6 +7,7 @@ import getPreviousStepsAction from '../../../controllers/api/v1/steps/get-previo
import createDynamicFieldsAction from '../../../controllers/api/v1/steps/create-dynamic-fields.js';
import createDynamicDataAction from '../../../controllers/api/v1/steps/create-dynamic-data.js';
import deleteStepAction from '../../../controllers/api/v1/steps/delete-step.js';
import updateStepAction from '../../../controllers/api/v1/steps/update-step.js';
const router = Router();
@@ -40,6 +41,7 @@ router.post(
createDynamicDataAction
);
router.patch('/:stepId', authenticateUser, authorizeUser, updateStepAction);
router.delete('/:stepId', authenticateUser, authorizeUser, deleteStepAction);
export default router;

View File

@@ -0,0 +1,26 @@
const updateStepMock = (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 updateStepMock;

View File

@@ -1,18 +1,17 @@
import * as React from 'react';
import { useMutation } from '@apollo/client';
import Box from '@mui/material/Box';
import IconButton from '@mui/material/IconButton';
import AddIcon from '@mui/icons-material/Add';
import useCreateStep from 'hooks/useCreateStep';
import { UPDATE_STEP } from 'graphql/mutations/update-step';
import useUpdateStep from 'hooks/useUpdateStep';
import FlowStep from 'components/FlowStep';
import { FlowPropType } from 'propTypes/propTypes';
import { useQueryClient } from '@tanstack/react-query';
function Editor(props) {
const [updateStep] = useMutation(UPDATE_STEP);
const { flow } = props;
const { mutateAsync: updateStep } = useUpdateStep();
const { mutateAsync: createStep, isPending: isCreateStepPending } =
useCreateStep(flow?.id);
const [triggerStep] = flow.steps;
@@ -21,29 +20,24 @@ function Editor(props) {
const onStepChange = React.useCallback(
async (step) => {
const mutationInput = {
const payload = {
id: step.id,
key: step.key,
parameters: step.parameters,
connection: {
id: step.connection?.id,
},
flow: {
id: flow.id,
},
connectionId: step.connection?.id,
};
if (step.appKey) {
mutationInput.appKey = step.appKey;
payload.appKey = step.appKey;
}
await updateStep({ variables: { input: mutationInput } });
await updateStep(payload);
await queryClient.invalidateQueries({
queryKey: ['steps', step.id, 'connection'],
});
await queryClient.invalidateQueries({ queryKey: ['flows', flow.id] });
},
[updateStep, flow.id, queryClient],
[updateStep, queryClient],
);
const addStep = React.useCallback(

View File

@@ -5,8 +5,8 @@ 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 useCreateStep from 'hooks/useCreateStep';
import useUpdateStep from 'hooks/useUpdateStep';
import { useAutoLayout } from './useAutoLayout';
import { useScrollBoundaries } from './useScrollBoundaries';
@@ -35,7 +35,7 @@ const edgeTypes = {
};
const EditorNew = ({ flow }) => {
const [updateStep] = useMutation(UPDATE_STEP);
const { mutateAsync: updateStep } = useUpdateStep();
const queryClient = useQueryClient();
const { mutateAsync: createStep, isPending: isCreateStepPending } =
@@ -84,31 +84,24 @@ const EditorNew = ({ flow }) => {
const onStepChange = useCallback(
async (step) => {
const mutationInput = {
const payload = {
id: step.id,
key: step.key,
parameters: step.parameters,
connection: {
id: step.connection?.id,
},
flow: {
id: flow.id,
},
connectionId: step.connection?.id,
};
if (step.appKey) {
mutationInput.appKey = step.appKey;
payload.appKey = step.appKey;
}
await updateStep({
variables: { input: mutationInput },
});
await updateStep(payload);
await queryClient.invalidateQueries({
queryKey: ['steps', step.id, 'connection'],
});
await queryClient.invalidateQueries({ queryKey: ['flows', flow.id] });
},
[flow.id, updateStep, queryClient],
[updateStep, queryClient],
);
const onAddStep = useCallback(

View File

@@ -1,17 +0,0 @@
import { gql } from '@apollo/client';
export const UPDATE_STEP = gql`
mutation UpdateStep($input: UpdateStepInput) {
updateStep(input: $input) {
id
type
key
appKey
parameters
status
webhookUrl
connection {
id
}
}
}
`;

View File

@@ -0,0 +1,28 @@
import { useMutation, useQueryClient } from '@tanstack/react-query';
import api from 'helpers/api';
export default function useUpdateStep() {
const queryClient = useQueryClient();
const query = useMutation({
mutationFn: async ({ id, appKey, key, connectionId, parameters }) => {
const { data } = await api.patch(`/v1/steps/${id}`, {
appKey,
key,
connectionId,
parameters,
});
return data;
},
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: ['flows'],
});
},
});
return query;
}