n8n/packages/nodes-base/nodes/Mailchimp/GenericFunctions.ts
Iván Ovejero 1d27a9e87e
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

* 🚧 create basic setup NodeError

* 🚧 add httpCodes

* 🚧 add path priolist

* 🚧 handle statusCode in error, adjust interfaces

* 🚧 fixing type issues w/Ivan

* 🚧 add error exploration

* 👔 fix linter issues

* 🔧 improve object check

* 🚧 remove path passing from NodeApiError

* 🚧 add multi error + refactor findProperty method

* 👔 allow any

* 🔧 handle multi error message callback

*  change return type of callback

*  add customCallback to MultiError

* 🚧 refactor to use INode

* 🔨 handle arrays, continue search after first null property found

* 🚫 refactor method access

* 🚧 setup NodeErrorView

*  change timestamp to Date.now

* 📚 Add documentation for methods and constants

* 🚧 change message setting

* 🚚 move NodeErrors to workflow

*  add new ErrorView for Nodes

* 🎨 improve error notification

* 🎨 refactor interfaces

*  add WorkflowOperationError, refactor error throwing

* 👕 fix linter issues

* 🎨 rename param

* 🐛 fix handling normal errors

*  add usage of NodeApiError

* 🎨 fix throw new error instead of constructor

* 🎨 remove unnecessary code/comments

* 🎨 adjusted spacing + updated status messages

* 🎨 fix tab indentation

*  Replace current errors with custom errors (#1576)

*  Introduce NodeApiError in catch blocks

*  Introduce NodeOperationError in nodes

*  Add missing errors and remove incompatible

*  Fix NodeOperationError in incompatible nodes

* 🔧 Adjust error handling in missed nodes

PayPal, FileMaker, Reddit, Taiga and Facebook Graph API nodes

* 🔨 Adjust Strava Trigger node error handling

* 🔨 Adjust AWS nodes error handling

* 🔨 Remove duplicate instantiation of NodeApiError

* 🐛 fix strava trigger node error handling

* Add XML parsing to NodeApiError constructor (#1633)

* 🐛 Remove type annotation from catch variable

*  Add XML parsing to NodeApiError

*  Simplify error handling in Rekognition node

*  Pass in XML flag in generic functions

* 🔥 Remove try/catch wrappers at call sites

* 🔨 Refactor setting description from XML

* 🔨 Refactor let to const in resource loaders

*  Find property in parsed XML

*  Change let to const

* 🔥 Remove unneeded try/catch block

* 👕 Fix linting issues

* 🐛 Fix errors from merge conflict resolution

*  Add custom errors to latest contributions

* 👕 Fix linting issues

*  Refactor MongoDB helpers for custom errors

* 🐛 Correct custom error type

*  Apply feedback to A nodes

*  Apply feedback to missed A node

*  Apply feedback to B-D nodes

*  Apply feedback to E-F nodes

*  Apply feedback to G nodes

*  Apply feedback to H-L nodes

*  Apply feedback to M nodes

*  Apply feedback to P nodes

*  Apply feedback to R nodes

*  Apply feedback to S nodes

*  Apply feedback to T nodes

*  Apply feedback to V-Z nodes

*  Add HTTP code to iterable node error

* 🔨 Standardize e as error

* 🔨 Standardize err as error

*  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 18:33:36 +02:00

171 lines
5.1 KiB
TypeScript

import {
OptionsWithUrl,
} from 'request';
import {
IExecuteFunctions,
IExecuteSingleFunctions,
IHookFunctions,
ILoadOptionsFunctions,
} from 'n8n-core';
import {
IDataObject, NodeApiError, NodeOperationError,
} from 'n8n-workflow';
export async function mailchimpApiRequest(this: IHookFunctions | IExecuteFunctions | IExecuteSingleFunctions | ILoadOptionsFunctions, endpoint: string, method: string, body: any = {}, qs: IDataObject = {} ,headers?: object): Promise<any> { // tslint:disable-line:no-any
const authenticationMethod = this.getNodeParameter('authentication', 0) as string;
const host = 'api.mailchimp.com/3.0';
const options: OptionsWithUrl = {
headers: {
'Accept': 'application/json',
},
method,
qs,
body,
url: ``,
json: true,
};
if (Object.keys(body).length === 0) {
delete options.body;
}
try {
if (authenticationMethod === 'apiKey') {
const credentials = this.getCredentials('mailchimpApi');
if (credentials === undefined) {
throw new NodeOperationError(this.getNode(), 'No credentials got returned!');
}
options.headers = Object.assign({}, headers, { Authorization: `apikey ${credentials.apiKey}` });
if (!(credentials.apiKey as string).includes('-')) {
throw new NodeOperationError(this.getNode(), 'The API key is not valid!');
}
const datacenter = (credentials.apiKey as string).split('-').pop();
options.url = `https://${datacenter}.${host}${endpoint}`;
return await this.helpers.request!(options);
} else {
const credentials = this.getCredentials('mailchimpOAuth2Api') as IDataObject;
const { api_endpoint } = await getMetadata.call(this, credentials.oauthTokenData as IDataObject);
options.url = `${api_endpoint}/3.0${endpoint}`;
//@ts-ignore
return await this.helpers.requestOAuth2!.call(this, 'mailchimpOAuth2Api', options, { tokenType: 'Bearer' });
}
} catch (error) {
throw new NodeApiError(this.getNode(), error);
}
}
export async function mailchimpApiRequestAllItems(this: IExecuteFunctions | ILoadOptionsFunctions, endpoint: string, method: string, propertyName: string, body: any = {}, query: IDataObject = {}): Promise<any> { // tslint:disable-line:no-any
const returnData: IDataObject[] = [];
let responseData;
query.offset = 0;
query.count = 500;
do {
responseData = await mailchimpApiRequest.call(this, endpoint, method, body, query);
returnData.push.apply(returnData, responseData[propertyName]);
query.offset += query.count;
} while (
responseData[propertyName] && responseData[propertyName].length !== 0
);
return returnData;
}
export function validateJSON(json: string | undefined): any { // tslint:disable-line:no-any
let result;
try {
result = JSON.parse(json!);
} catch (exception) {
result = '';
}
return result;
}
function getMetadata(this: IHookFunctions | IExecuteFunctions | IExecuteSingleFunctions | ILoadOptionsFunctions, oauthTokenData: IDataObject) {
const credentials = this.getCredentials('mailchimpOAuth2Api') as IDataObject;
const options: OptionsWithUrl = {
headers: {
'Accept': 'application/json',
'Authorization': `OAuth ${oauthTokenData.access_token}`,
},
method: 'GET',
url: credentials.metadataUrl as string,
json: true,
};
return this.helpers.request!(options);
}
export const campaignFieldsMetadata = [
'*',
'campaigns.id',
'campaigns.web_id',
'campaigns.type',
'campaigns.create_time',
'campaigns.archive_url',
'campaigns.long_archive_url',
'campaigns.status',
'campaigns.emails_sent',
'campaigns.send_time',
'campaigns.content_type',
'campaigns.needs_block_refresh',
'campaigns.resendable',
'campaigns.recipients',
'campaigns.recipients.list_id',
'campaigns.recipients.list_is_active',
'campaigns.recipients.list_name',
'campaigns.recipients.segment_text',
'campaigns.recipients.recipient_count',
'campaigns.settings',
'campaigns.settings.subject_line',
'campaigns.settings.preview_text',
'campaigns.settings.title',
'campaigns.settings.from_name',
'campaigns.settings.reply_to',
'campaigns.settings.use_conversation',
'campaigns.settings.to_name',
'campaigns.settings.folder_id',
'campaigns.settings.authenticate',
'campaigns.settings.auto_footer',
'campaigns.settings.inline_css',
'campaigns.settings.auto_tweet',
'campaigns.settings.fb_comments',
'campaigns.settings.timewarp',
'campaigns.settings.template_id',
'campaigns.settings.drag_and_drop',
'campaigns.tracking',
'campaigns.tracking.opens',
'campaigns.tracking.html_clicks',
'campaigns.tracking.text_clicks',
'campaigns.tracking.goal_tracking',
'campaigns.tracking.ecomm360',
'campaigns.tracking.google_analytics',
'campaigns.tracking.clicktale',
'campaigns.report_summary',
'campaigns.report_summary.opens',
'campaigns.report_summary.unique_opens',
'campaigns.report_summary.open_rate',
'campaigns.report_summary.clicks',
'campaigns.report_summary.subscriber_clicks',
'campaigns.report_summary.click_rate',
'campaigns.report_summary.click_rate.ecommerce',
'campaigns.report_summary.click_rate.ecommerce.total_orders',
'campaigns.report_summary.click_rate.ecommerce.total_spent',
'campaigns.report_summary.click_rate.ecommerce.total_revenue',
'campaigns.report_summary.delivery_status.enabled',
'campaigns._links',
];