Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(GraphQL Node): Throw error if GraphQL variables are not objects or strings #11904

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
88 changes: 45 additions & 43 deletions packages/nodes-base/nodes/GraphQL/GraphQL.node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -418,40 +418,45 @@ export class GraphQL implements INodeType {

const gqlQuery = this.getNodeParameter('query', itemIndex, '') as string;
if (requestMethod === 'GET') {
if (!requestOptions.qs) {
requestOptions.qs = {};
}
requestOptions.qs = requestOptions.qs ?? {};
requestOptions.qs.query = gqlQuery;
} else {
if (requestFormat === 'json') {
const jsonBody = {
...requestOptions.body,
query: gqlQuery,
variables: this.getNodeParameter('variables', itemIndex, {}) as object,
operationName: this.getNodeParameter('operationName', itemIndex) as string,
};
if (typeof jsonBody.variables === 'string') {
try {
jsonBody.variables = JSON.parse(jsonBody.variables || '{}');
} catch (error) {
throw new NodeOperationError(
this.getNode(),
'Using variables failed:\n' +
(jsonBody.variables as string) +
'\n\nWith error message:\n' +
(error as string),
{ itemIndex },
);
}
}
if (jsonBody.operationName === '') {
jsonBody.operationName = null;
}

if (requestFormat === 'json') {
const variables = this.getNodeParameter('variables', itemIndex, {});

let parsedVariables;
if (typeof variables === 'string') {
try {
parsedVariables = JSON.parse(variables || '{}');
} catch (error) {
throw new NodeOperationError(
this.getNode(),
`Using variables failed:\n${variables}\n\nWith error message:\n${error}`,
{ itemIndex },
);
}
requestOptions.json = true;
requestOptions.body = jsonBody;
} else if (typeof variables === 'object' && variables !== null) {
parsedVariables = variables;
} else {
requestOptions.body = gqlQuery;
throw new NodeOperationError(
this.getNode(),
`Using variables failed:\n${variables}\n\nGraphQL variables should be either an object or a string.`,
{ itemIndex },
);
}

const jsonBody = {
...requestOptions.body,
query: gqlQuery,
variables: parsedVariables,
operationName: this.getNodeParameter('operationName', itemIndex) as string,
};

requestOptions.json = true;
requestOptions.body = jsonBody;
} else {
requestOptions.body = gqlQuery;
}

let response;
Expand Down Expand Up @@ -509,22 +514,19 @@ export class GraphQL implements INodeType {
throw new NodeApiError(this.getNode(), response.errors as JsonObject, { message });
}
} catch (error) {
if (this.continueOnFail()) {
const errorData = this.helpers.returnJsonArray({
$error: error,
json: this.getInputData(itemIndex),
itemIndex,
});
const exectionErrorWithMetaData = this.helpers.constructExecutionMetaData(errorData, {
itemData: { item: itemIndex },
});
returnItems.push(...exectionErrorWithMetaData);
continue;
if (!this.continueOnFail) {
throw error;
}
throw error;

const errorData = this.helpers.returnJsonArray({
error: error.message,
});
const exectionErrorWithMetaData = this.helpers.constructExecutionMetaData(errorData, {
itemData: { item: itemIndex },
});
returnItems.push(...exectionErrorWithMetaData);
}
}

return [returnItems];
}
}
70 changes: 22 additions & 48 deletions packages/nodes-base/nodes/GraphQL/test/GraphQL.node.test.ts
Original file line number Diff line number Diff line change
@@ -1,54 +1,28 @@
import type { WorkflowTestData } from '@test/nodes/types';
import { executeWorkflow } from '@test/nodes/ExecuteWorkflow';
import * as Helpers from '@test/nodes/Helpers';
import {
equalityTest,
getWorkflowFilenames,
initBinaryDataService,
setup,
workflowToTests,
} from '@test/nodes/Helpers';
import nock from 'nock';

describe('GraphQL Node', () => {
const mockResponse = {
data: {
nodes: {},
},
};
const workflows = getWorkflowFilenames(__dirname);
const workflowTests = workflowToTests(workflows);

const tests: WorkflowTestData[] = [
{
description: 'should run Request Format JSON',
input: {
workflowData: Helpers.readJsonFileSync('nodes/GraphQL/test/workflow.json'),
},
output: {
nodeExecutionOrder: ['Start'],
nodeData: {
'Fetch Request Format JSON': [
[
{
json: mockResponse,
},
],
],
},
},
nock: {
baseUrl: 'https://api.n8n.io',
mocks: [
{
method: 'post',
path: '/graphql',
statusCode: 200,
responseBody: mockResponse,
},
],
},
},
];

const nodeTypes = Helpers.setup(tests);
beforeAll(async () => {
await initBinaryDataService();
nock.disableNetConnect();
});

test.each(tests)('$description', async (testData) => {
const { result } = await executeWorkflow(testData, nodeTypes);
const resultNodeData = Helpers.getResultNodeData(result, testData);
resultNodeData.forEach(({ nodeName, resultData }) =>
expect(resultData).toEqual(testData.output.nodeData[nodeName]),
);
expect(result.finished).toEqual(true);
afterAll(() => {
nock.restore();
});

const nodeTypes = setup(workflowTests);

for (const workflow of workflowTests) {
test(workflow.description, async () => await equalityTest(workflow, nodeTypes));
}
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
{
"meta": {
"templateId": "216",
"instanceId": "ee90fdf8d57662f949e6c691dc07fa0fd2f66e1eee28ed82ef06658223e67255"
},
"nodes": [
{
"parameters": {
"endpoint": "https://graphql-teas-endpoint.netlify.app/",
"requestFormat": "json",
"query": "query getAllTeas($name: String) {\n teas(name: $name) {\n name,\n id\n }\n}",
"variables": "={{ 1 }}"
},
"id": "7aece03f-e0d9-4f49-832c-fc6465613ca7",
"name": "Test: Errors on unsuccessful Expression validation",
"type": "n8n-nodes-base.graphql",
"typeVersion": 1,
"position": [660, 200],
"onError": "continueRegularOutput"
}
],
"connections": {},
"pinData": {
"Test: Errors on unsuccessful Expression validation": [
{
"json": {
"error": "Using variables failed:\n1\n\nGraphQL variables should be either an object or a string."
}
}
]
}
}