n8n/packages/nodes-base/nodes/Mailchimp/GenericFunctions.ts

162 lines
5 KiB
TypeScript
Raw Normal View History

2020-05-22 06:47:47 -07:00
import {
2020-06-04 06:54:39 -07:00
OptionsWithUrl,
2020-05-22 06:47:47 -07:00
} from 'request';
2019-11-12 12:48:45 -08:00
import {
IExecuteFunctions,
2020-05-22 06:47:47 -07:00
IExecuteSingleFunctions,
2019-11-12 12:48:45 -08:00
IHookFunctions,
ILoadOptionsFunctions,
} from 'n8n-core';
2020-05-22 06:47:47 -07:00
import {
: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
IDataObject, NodeApiError, NodeOperationError,
2020-05-22 06:47:47 -07:00
} 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
2020-06-04 06:54:39 -07:00
const authenticationMethod = this.getNodeParameter('authentication', 0) as string;
const host = 'api.mailchimp.com/3.0';
2019-11-12 12:48:45 -08:00
2020-06-04 06:54:39 -07:00
const options: OptionsWithUrl = {
headers: {
2020-10-22 06:46:03 -07:00
'Accept': 'application/json',
2020-06-04 06:54:39 -07:00
},
2019-11-12 12:48:45 -08:00
method,
2020-05-22 06:47:47 -07:00
qs,
2020-06-04 06:54:39 -07:00
body,
url: ``,
json: true,
2019-11-12 12:48:45 -08:00
};
2020-06-04 06:54:39 -07:00
if (Object.keys(body).length === 0) {
delete options.body;
2019-11-12 12:48:45 -08:00
}
2020-06-04 06:54:39 -07:00
2019-11-12 12:48:45 -08:00
try {
2020-06-13 19:37:03 -07:00
if (authenticationMethod === 'apiKey') {
const credentials = await this.getCredentials('mailchimpApi');
2020-06-04 06:54:39 -07:00
if (!(credentials.apiKey as string).includes('-')) {
: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
throw new NodeOperationError(this.getNode(), 'The API key is not valid!');
2020-06-04 06:54:39 -07:00
}
const datacenter = (credentials.apiKey as string).split('-').pop();
options.url = `https://${datacenter}.${host}${endpoint}`;
feat: Add more credentials tests (#3668) * ✨ Add injection to notion, Add test to notion in cred * 🔥 Remove unuse method * 🎨 Move testing from node file to cred file * ✨ Add injection and testing in facebook graph * Add cred injec with testing * Add Cred injection and cred test * Add cred injection, and cred testing for typeform, fix issue in clickup * Add cred injection, move testing inside creds * Add cred injection and cred testing to SendGrid * Add cred injection and cred testing to woocommerce * Add cred injection, add cred test to gitlab * 🔥 Fix duplicated imports in Mautic cred * 🔥 removed unused credentials testing in node * Add cred injection, cred testing, handles slash trailing for Grafana node * Add cred injection, cred testing to shopify * Add cred injection , add cred testing to stripe * changed cred injection, add testing to cred for mattermost * add cred injection and testing for dropbox * Add cred injection, cred testing to webflow * ✨ Add cred injection and cred test to nocodb * ✨ Add cred injection, cred testing to mailchimp * 🐛 fix a bug In credentials testing * ✨ Add cred injection, cred testing to sms77 * ✨ Add cred injection, cred testing to ActiveCampaign * Add cred injection, cred testing to TheHive * ✨ Add cred injection, add cred testing to ApiTemplateio * ✨ Add cred injection, add cred testing for zoom * ✨ Add cred injection, cred testing to rocketchat * ✨ Add cred injection, add cred test to getResponse * 🔥 Remove useless authentcate creds and testing from facebookGraphApp * 🔥 Remove useless imports in FacebookGrappApp credentials file * 🔥 Removed useless imports and if statement * 🐛 Add version to header when testing cred Co-authored-by: Omar Ajoue <krynble@gmail.com> Co-authored-by: Jan Oberhauser <janober@users.noreply.github.com>
2022-07-15 07:20:41 -07:00
return await this.helpers.requestWithAuthentication.call(this, 'mailchimpApi', options);
2020-06-04 06:54:39 -07:00
} else {
const credentials = await this.getCredentials('mailchimpOAuth2Api');
2020-06-13 19:37:03 -07:00
const { api_endpoint } = await getMetadata.call(this, credentials.oauthTokenData as IDataObject);
options.url = `${api_endpoint}/3.0${endpoint}`;
2020-06-04 06:54:39 -07:00
//@ts-ignore
return await this.helpers.requestOAuth2!.call(this, 'mailchimpOAuth2Api', options, { tokenType: 'Bearer' });
2020-06-04 06:54:39 -07:00
}
2019-11-12 12:48:45 -08:00
} catch (error) {
: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
throw new NodeApiError(this.getNode(), error);
2019-11-12 12:48:45 -08:00
}
}
2019-11-14 15:44:07 -08:00
2020-05-22 06:47:47 -07:00
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;
}
2019-11-14 15:44:07 -08:00
export function validateJSON(json: string | undefined): any { // tslint:disable-line:no-any
let result;
try {
result = JSON.parse(json!);
} catch (exception) {
result = '';
}
return result;
}
2020-06-13 19:37:03 -07:00
async function getMetadata(this: IHookFunctions | IExecuteFunctions | IExecuteSingleFunctions | ILoadOptionsFunctions, oauthTokenData: IDataObject) {
const credentials = await this.getCredentials('mailchimpOAuth2Api');
2020-06-13 19:37:03 -07:00
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);
}
2020-10-05 15:44:52 -07:00
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',
];