n8n/packages/nodes-base/nodes/GraphQL/GraphQL.node.ts

320 lines
7.4 KiB
TypeScript
Raw Normal View History

2019-10-30 04:05:52 -07:00
import { IExecuteFunctions } from 'n8n-core';
import {
IDataObject,
2019-10-30 04:05:52 -07:00
INodeExecutionData,
INodeType,
INodeTypeDescription,
:sparkles: Improve node error handling (#1309) * Add path mapping and response error interfaces * Add error handling and throwing functionality * Refactor error handling into a single function * Re-implement error handling in Hacker News node * Fix linting details * Re-implement error handling in Spotify node * Re-implement error handling in G Suite Admin node * :construction: create basic setup NodeError * :construction: add httpCodes * :construction: add path priolist * :construction: handle statusCode in error, adjust interfaces * :construction: fixing type issues w/Ivan * :construction: add error exploration * 👔 fix linter issues * :wrench: improve object check * :construction: remove path passing from NodeApiError * :construction: add multi error + refactor findProperty method * 👔 allow any * :wrench: handle multi error message callback * :zap: change return type of callback * :zap: add customCallback to MultiError * :construction: refactor to use INode * :hammer: handle arrays, continue search after first null property found * 🚫 refactor method access * :construction: setup NodeErrorView * :zap: change timestamp to Date.now * :books: Add documentation for methods and constants * :construction: change message setting * 🚚 move NodeErrors to workflow * :sparkles: add new ErrorView for Nodes * :art: improve error notification * :art: refactor interfaces * :zap: add WorkflowOperationError, refactor error throwing * 👕 fix linter issues * :art: rename param * :bug: fix handling normal errors * :zap: add usage of NodeApiError * :art: fix throw new error instead of constructor * :art: remove unnecessary code/comments * :art: adjusted spacing + updated status messages * :art: fix tab indentation * ✨ Replace current errors with custom errors (#1576) * :zap: Introduce NodeApiError in catch blocks * :zap: Introduce NodeOperationError in nodes * :zap: Add missing errors and remove incompatible * :zap: Fix NodeOperationError in incompatible nodes * :wrench: Adjust error handling in missed nodes PayPal, FileMaker, Reddit, Taiga and Facebook Graph API nodes * :hammer: Adjust Strava Trigger node error handling * :hammer: Adjust AWS nodes error handling * :hammer: Remove duplicate instantiation of NodeApiError * :bug: fix strava trigger node error handling * Add XML parsing to NodeApiError constructor (#1633) * :bug: Remove type annotation from catch variable * :sparkles: Add XML parsing to NodeApiError * :zap: Simplify error handling in Rekognition node * :zap: Pass in XML flag in generic functions * :fire: Remove try/catch wrappers at call sites * :hammer: Refactor setting description from XML * :hammer: Refactor let to const in resource loaders * :zap: Find property in parsed XML * :zap: Change let to const * :fire: Remove unneeded try/catch block * :shirt: Fix linting issues * :bug: Fix errors from merge conflict resolution * :zap: Add custom errors to latest contributions * :shirt: Fix linting issues * :zap: Refactor MongoDB helpers for custom errors * :bug: Correct custom error type * :zap: Apply feedback to A nodes * :zap: Apply feedback to missed A node * :zap: Apply feedback to B-D nodes * :zap: Apply feedback to E-F nodes * :zap: Apply feedback to G nodes * :zap: Apply feedback to H-L nodes * :zap: Apply feedback to M nodes * :zap: Apply feedback to P nodes * :zap: Apply feedback to R nodes * :zap: Apply feedback to S nodes * :zap: Apply feedback to T nodes * :zap: Apply feedback to V-Z nodes * :zap: Add HTTP code to iterable node error * :hammer: Standardize e as error * :hammer: Standardize err as error * :zap: Fix error handling for non-standard nodes Co-authored-by: Ben Hesseldieck <b.hesseldieck@gmail.com> Co-authored-by: Ben Hesseldieck <b.hesseldieck@gmail.com> Co-authored-by: Ben Hesseldieck <1849459+BHesseldieck@users.noreply.github.com>
2021-04-16 09:33:36 -07:00
NodeApiError,
NodeOperationError,
2019-10-30 04:05:52 -07:00
} from 'n8n-workflow';
import { OptionsWithUri } from 'request';
import { RequestPromiseOptions } from 'request-promise-native';
export class GraphQL implements INodeType {
description: INodeTypeDescription = {
displayName: 'GraphQL',
name: 'graphql',
icon: 'file:graphql.png',
2019-10-30 04:05:52 -07:00
group: ['input'],
version: 1,
description: 'Makes a GraphQL request and returns the received data',
defaults: {
name: 'GraphQL',
color: '#E10098',
},
inputs: ['main'],
outputs: ['main'],
credentials: [
{
name: 'httpHeaderAuth',
required: true,
displayOptions: {
show: {
authentication: [
'headerAuth',
],
},
},
},
],
2019-10-30 04:05:52 -07:00
properties: [
{
displayName: 'Authentication',
name: 'authentication',
type: 'options',
options: [
{
name: 'Header Auth',
value: 'headerAuth',
},
{
name: 'None',
value: 'none',
},
],
default: 'none',
description: 'The way to authenticate.',
},
2019-10-30 04:05:52 -07:00
{
displayName: 'HTTP Request Method',
name: 'requestMethod',
type: 'options',
options: [
{
name: 'GET',
value: 'GET',
2019-10-30 04:05:52 -07:00
},
{
name: 'POST',
value: 'POST',
2019-10-30 04:05:52 -07:00
},
],
default: 'POST',
description: 'The underlying HTTP request method to use.',
},
{
displayName: 'Endpoint',
name: 'endpoint',
type: 'string',
default: '',
placeholder: 'http://example.com/graphql',
description: 'The GraphQL endpoint.',
required: true,
},
{
displayName: 'Ignore SSL Issues',
name: 'allowUnauthorizedCerts',
type: 'boolean',
default: false,
description: 'Still fetch the response even if SSL certificate validation is not possible.',
},
{
displayName: 'Request Format',
name: 'requestFormat',
type: 'options',
required: true,
options: [
{
name: 'GraphQL (raw)',
value: 'graphql',
2019-10-30 04:05:52 -07:00
},
{
name: 'JSON',
value: 'json',
2019-10-30 04:05:52 -07:00
},
],
displayOptions: {
show: {
requestMethod: [
'POST',
2019-10-30 04:05:52 -07:00
],
},
},
default: 'graphql',
description: 'The format for the query payload',
},
{
displayName: 'Query',
name: 'query',
type: 'json',
default: '',
description: 'GraphQL query',
required: true,
},
{
displayName: 'Variables',
name: 'variables',
type: 'json',
2019-10-30 06:02:14 -07:00
default: '',
2019-10-30 04:05:52 -07:00
description: 'Query variables',
displayOptions: {
show: {
requestFormat: [
'json',
2019-10-30 04:05:52 -07:00
],
requestMethod: [
'POST',
2019-10-30 04:05:52 -07:00
],
},
},
},
{
displayName: 'Operation Name',
name: 'operationName',
type: 'string',
default: '',
description: 'Name of operation to execute',
displayOptions: {
show: {
requestFormat: [
'json',
2019-10-30 04:05:52 -07:00
],
requestMethod: [
'POST',
2019-10-30 04:05:52 -07:00
],
},
},
},
{
displayName: 'Response Format',
name: 'responseFormat',
type: 'options',
options: [
{
name: 'JSON',
value: 'json',
2019-10-30 04:05:52 -07:00
},
{
name: 'String',
value: 'string',
2019-10-30 04:05:52 -07:00
},
],
default: 'json',
description: 'The format in which the data gets returned from the URL.',
},
{
displayName: 'Response Data Property Name',
name: 'dataPropertyName',
type: 'string',
2019-10-31 09:26:05 -07:00
default: 'data',
2019-10-30 04:05:52 -07:00
required: true,
displayOptions: {
show: {
responseFormat: [
'string',
],
},
},
description: 'Name of the property to which to write the response data.',
},
// Header Parameters
{
displayName: 'Headers',
name: 'headerParametersUi',
placeholder: 'Add Header',
type: 'fixedCollection',
typeOptions: {
multipleValues: true,
},
description: 'The headers to send.',
default: {},
options: [
{
name: 'parameter',
displayName: 'Header',
values: [
{
displayName: 'Name',
name: 'name',
type: 'string',
default: '',
description: 'Name of the header.',
},
{
displayName: 'Value',
name: 'value',
type: 'string',
default: '',
description: 'Value to set for the header.',
},
2020-10-22 06:46:03 -07:00
],
},
],
},
2020-10-22 06:46:03 -07:00
],
2019-10-30 04:05:52 -07:00
};
async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> {
const items = this.getInputData();
const httpHeaderAuth = this.getCredentials('httpHeaderAuth');
2019-10-30 04:05:52 -07:00
let requestOptions: OptionsWithUri & RequestPromiseOptions;
const returnItems: INodeExecutionData[] = [];
for (let itemIndex = 0; itemIndex < items.length; itemIndex++) {
const requestMethod = this.getNodeParameter('requestMethod', itemIndex, 'POST') as string;
const endpoint = this.getNodeParameter('endpoint', itemIndex, '') as string;
const requestFormat = this.getNodeParameter('requestFormat', itemIndex, 'graphql') as string;
2019-10-30 04:05:52 -07:00
const responseFormat = this.getNodeParameter('responseFormat', 0) as string;
2020-04-19 09:43:45 -07:00
const { parameter }: { parameter?: Array<{ name: string, value: string }> } = this
.getNodeParameter('headerParametersUi', itemIndex, {}) as IDataObject;
const headerParameters = (parameter || []).reduce((result, item) => ({
...result,
2020-10-22 06:46:03 -07:00
[item.name]: item.value,
}), {});
2019-10-30 04:05:52 -07:00
requestOptions = {
headers: {
'content-type': `application/${requestFormat}`,
2020-10-22 06:46:03 -07:00
...headerParameters,
2019-10-30 04:05:52 -07:00
},
method: requestMethod,
uri: endpoint,
simple: false,
rejectUnauthorized: !this.getNodeParameter('allowUnauthorizedCerts', itemIndex, false) as boolean,
};
// Add credentials if any are set
if (httpHeaderAuth !== undefined) {
requestOptions.headers![httpHeaderAuth.name as string] = httpHeaderAuth.value;
}
2019-10-30 04:05:52 -07:00
const gqlQuery = this.getNodeParameter('query', itemIndex, '') as string;
if (requestMethod === 'GET') {
requestOptions.qs = {
2020-10-22 06:46:03 -07:00
query: gqlQuery,
2019-10-30 04:05:52 -07:00
};
} else {
if (requestFormat === 'json') {
requestOptions.body = {
query: gqlQuery,
variables: this.getNodeParameter('variables', itemIndex, {}) as object,
operationName: this.getNodeParameter('operationName', itemIndex) as string,
2019-10-30 04:05:52 -07:00
};
if (typeof requestOptions.body.variables === 'string') {
2019-10-30 06:02:14 -07:00
try {
2020-11-20 07:51:46 -08:00
requestOptions.body.variables = JSON.parse(requestOptions.body.variables || '{}');
:sparkles: Improve node error handling (#1309) * Add path mapping and response error interfaces * Add error handling and throwing functionality * Refactor error handling into a single function * Re-implement error handling in Hacker News node * Fix linting details * Re-implement error handling in Spotify node * Re-implement error handling in G Suite Admin node * :construction: create basic setup NodeError * :construction: add httpCodes * :construction: add path priolist * :construction: handle statusCode in error, adjust interfaces * :construction: fixing type issues w/Ivan * :construction: add error exploration * 👔 fix linter issues * :wrench: improve object check * :construction: remove path passing from NodeApiError * :construction: add multi error + refactor findProperty method * 👔 allow any * :wrench: handle multi error message callback * :zap: change return type of callback * :zap: add customCallback to MultiError * :construction: refactor to use INode * :hammer: handle arrays, continue search after first null property found * 🚫 refactor method access * :construction: setup NodeErrorView * :zap: change timestamp to Date.now * :books: Add documentation for methods and constants * :construction: change message setting * 🚚 move NodeErrors to workflow * :sparkles: add new ErrorView for Nodes * :art: improve error notification * :art: refactor interfaces * :zap: add WorkflowOperationError, refactor error throwing * 👕 fix linter issues * :art: rename param * :bug: fix handling normal errors * :zap: add usage of NodeApiError * :art: fix throw new error instead of constructor * :art: remove unnecessary code/comments * :art: adjusted spacing + updated status messages * :art: fix tab indentation * ✨ Replace current errors with custom errors (#1576) * :zap: Introduce NodeApiError in catch blocks * :zap: Introduce NodeOperationError in nodes * :zap: Add missing errors and remove incompatible * :zap: Fix NodeOperationError in incompatible nodes * :wrench: Adjust error handling in missed nodes PayPal, FileMaker, Reddit, Taiga and Facebook Graph API nodes * :hammer: Adjust Strava Trigger node error handling * :hammer: Adjust AWS nodes error handling * :hammer: Remove duplicate instantiation of NodeApiError * :bug: fix strava trigger node error handling * Add XML parsing to NodeApiError constructor (#1633) * :bug: Remove type annotation from catch variable * :sparkles: Add XML parsing to NodeApiError * :zap: Simplify error handling in Rekognition node * :zap: Pass in XML flag in generic functions * :fire: Remove try/catch wrappers at call sites * :hammer: Refactor setting description from XML * :hammer: Refactor let to const in resource loaders * :zap: Find property in parsed XML * :zap: Change let to const * :fire: Remove unneeded try/catch block * :shirt: Fix linting issues * :bug: Fix errors from merge conflict resolution * :zap: Add custom errors to latest contributions * :shirt: Fix linting issues * :zap: Refactor MongoDB helpers for custom errors * :bug: Correct custom error type * :zap: Apply feedback to A nodes * :zap: Apply feedback to missed A node * :zap: Apply feedback to B-D nodes * :zap: Apply feedback to E-F nodes * :zap: Apply feedback to G nodes * :zap: Apply feedback to H-L nodes * :zap: Apply feedback to M nodes * :zap: Apply feedback to P nodes * :zap: Apply feedback to R nodes * :zap: Apply feedback to S nodes * :zap: Apply feedback to T nodes * :zap: Apply feedback to V-Z nodes * :zap: Add HTTP code to iterable node error * :hammer: Standardize e as error * :hammer: Standardize err as error * :zap: Fix error handling for non-standard nodes Co-authored-by: Ben Hesseldieck <b.hesseldieck@gmail.com> Co-authored-by: Ben Hesseldieck <b.hesseldieck@gmail.com> Co-authored-by: Ben Hesseldieck <1849459+BHesseldieck@users.noreply.github.com>
2021-04-16 09:33:36 -07:00
} catch (error) {
throw new NodeOperationError(this.getNode(), 'Using variables failed:\n' + requestOptions.body.variables + '\n\nWith error message:\n' + error);
2019-10-30 06:02:14 -07:00
}
2019-10-30 04:05:52 -07:00
}
if (requestOptions.body.operationName === '') {
requestOptions.body.operationName = null;
2019-10-30 04:05:52 -07:00
}
requestOptions.json = true;
} else {
requestOptions.body = gqlQuery;
}
}
const response = await this.helpers.request(requestOptions);
if (responseFormat === 'string') {
const dataPropertyName = this.getNodeParameter('dataPropertyName', 0) as string;
returnItems.push({
json: {
[dataPropertyName]: response,
2020-10-22 06:46:03 -07:00
},
2019-10-30 04:05:52 -07:00
});
} else {
if (typeof response === 'string') {
try {
returnItems.push({ json: JSON.parse(response) });
:sparkles: Improve node error handling (#1309) * Add path mapping and response error interfaces * Add error handling and throwing functionality * Refactor error handling into a single function * Re-implement error handling in Hacker News node * Fix linting details * Re-implement error handling in Spotify node * Re-implement error handling in G Suite Admin node * :construction: create basic setup NodeError * :construction: add httpCodes * :construction: add path priolist * :construction: handle statusCode in error, adjust interfaces * :construction: fixing type issues w/Ivan * :construction: add error exploration * 👔 fix linter issues * :wrench: improve object check * :construction: remove path passing from NodeApiError * :construction: add multi error + refactor findProperty method * 👔 allow any * :wrench: handle multi error message callback * :zap: change return type of callback * :zap: add customCallback to MultiError * :construction: refactor to use INode * :hammer: handle arrays, continue search after first null property found * 🚫 refactor method access * :construction: setup NodeErrorView * :zap: change timestamp to Date.now * :books: Add documentation for methods and constants * :construction: change message setting * 🚚 move NodeErrors to workflow * :sparkles: add new ErrorView for Nodes * :art: improve error notification * :art: refactor interfaces * :zap: add WorkflowOperationError, refactor error throwing * 👕 fix linter issues * :art: rename param * :bug: fix handling normal errors * :zap: add usage of NodeApiError * :art: fix throw new error instead of constructor * :art: remove unnecessary code/comments * :art: adjusted spacing + updated status messages * :art: fix tab indentation * ✨ Replace current errors with custom errors (#1576) * :zap: Introduce NodeApiError in catch blocks * :zap: Introduce NodeOperationError in nodes * :zap: Add missing errors and remove incompatible * :zap: Fix NodeOperationError in incompatible nodes * :wrench: Adjust error handling in missed nodes PayPal, FileMaker, Reddit, Taiga and Facebook Graph API nodes * :hammer: Adjust Strava Trigger node error handling * :hammer: Adjust AWS nodes error handling * :hammer: Remove duplicate instantiation of NodeApiError * :bug: fix strava trigger node error handling * Add XML parsing to NodeApiError constructor (#1633) * :bug: Remove type annotation from catch variable * :sparkles: Add XML parsing to NodeApiError * :zap: Simplify error handling in Rekognition node * :zap: Pass in XML flag in generic functions * :fire: Remove try/catch wrappers at call sites * :hammer: Refactor setting description from XML * :hammer: Refactor let to const in resource loaders * :zap: Find property in parsed XML * :zap: Change let to const * :fire: Remove unneeded try/catch block * :shirt: Fix linting issues * :bug: Fix errors from merge conflict resolution * :zap: Add custom errors to latest contributions * :shirt: Fix linting issues * :zap: Refactor MongoDB helpers for custom errors * :bug: Correct custom error type * :zap: Apply feedback to A nodes * :zap: Apply feedback to missed A node * :zap: Apply feedback to B-D nodes * :zap: Apply feedback to E-F nodes * :zap: Apply feedback to G nodes * :zap: Apply feedback to H-L nodes * :zap: Apply feedback to M nodes * :zap: Apply feedback to P nodes * :zap: Apply feedback to R nodes * :zap: Apply feedback to S nodes * :zap: Apply feedback to T nodes * :zap: Apply feedback to V-Z nodes * :zap: Add HTTP code to iterable node error * :hammer: Standardize e as error * :hammer: Standardize err as error * :zap: Fix error handling for non-standard nodes Co-authored-by: Ben Hesseldieck <b.hesseldieck@gmail.com> Co-authored-by: Ben Hesseldieck <b.hesseldieck@gmail.com> Co-authored-by: Ben Hesseldieck <1849459+BHesseldieck@users.noreply.github.com>
2021-04-16 09:33:36 -07:00
} catch (error) {
throw new NodeOperationError(this.getNode(), 'Response body is not valid JSON. Change "Response Format" to "String"');
}
} else {
returnItems.push({ json: response });
2019-10-30 04:05:52 -07:00
}
}
}
return this.prepareOutputData(returnItems);
}
}