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

100 lines
2.4 KiB
TypeScript
Raw Normal View History

import {
OptionsWithUri,
} from 'request';
2019-10-26 09:58:04 -07:00
import {
IExecuteFunctions,
IHookFunctions,
ILoadOptionsFunctions,
2019-10-26 09:58:04 -07:00
} from 'n8n-core';
import * as _ from 'lodash';
export async function mandrillApiRequest(this: IExecuteFunctions | IHookFunctions | ILoadOptionsFunctions, resource: string, method: string, action: string, body: any = {}, headers?: object): Promise<any> { // tslint:disable-line:no-any
const credentials = this.getCredentials('mandrillApi');
2019-10-26 09:58:04 -07:00
if (credentials === undefined) {
2019-10-26 09:58:04 -07:00
throw new Error('No credentials got returned!');
}
const data = Object.assign({}, body, { key: credentials.apiKey });
2019-10-26 09:58:04 -07:00
const endpoint = 'mandrillapp.com/api/1.0';
const options: OptionsWithUri = {
2019-11-04 09:29:20 -08:00
headers,
2019-10-26 09:58:04 -07:00
method,
uri: `https://${endpoint}${resource}${action}.json`,
body: data,
2020-10-22 06:46:03 -07:00
json: true,
};
2019-10-26 09:58:04 -07:00
try {
return await this.helpers.request!(options);
2019-10-26 09:58:04 -07:00
} catch (error) {
const errorMessage = error.response.body.message || error.response.body.Message;
if (error.name === 'Invalid_Key') {
throw new Error('The provided API key is not a valid Mandrill API key');
} else if (error.name === 'ValidationError') {
throw new Error('The parameters passed to the API call are invalid or not provided when required');
} else if (error.name === 'GeneralError') {
2019-10-26 09:58:04 -07:00
throw new Error('An unexpected error occurred processing the request. Mandrill developers will be notified.');
}
2019-10-26 09:58:04 -07:00
if (errorMessage !== undefined) {
throw errorMessage;
}
throw error.response.body;
}
2019-10-26 09:58:04 -07:00
}
2019-10-28 14:23:25 -07:00
export function getToEmailArray(toEmail: string): any { // tslint:disable-line:no-any
let toEmailArray;
if (toEmail.split(',').length > 0) {
const array = toEmail.split(',');
toEmailArray = _.map(array, (email) => {
return {
email,
2020-10-22 06:46:03 -07:00
type: 'to',
};
});
} else {
toEmailArray = [{
email: toEmail,
2020-10-22 06:46:03 -07:00
type: 'to',
}];
}
return toEmailArray;
}
2019-10-28 14:23:25 -07:00
export function getGoogleAnalyticsDomainsArray(s: string): string[] {
let array: string[] = [];
if (s.split(',').length > 0) {
array = s.split(',');
} else {
array = [s];
}
return array;
}
2019-10-28 14:23:25 -07:00
export function getTags(s: string): any[] { // tslint:disable-line:no-any
let array = [];
if (s.split(',').length > 0) {
array = s.split(',');
} else {
array = [s];
}
return array;
}
export function validateJSON(json: string | undefined): any { // tslint:disable-line:no-any
let result;
try {
result = JSON.parse(json!);
} catch (exception) {
result = [];
}
return result;
}