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

59 lines
1.5 KiB
TypeScript
Raw Normal View History

2019-11-12 12:48:45 -08:00
import { OptionsWithUri } from 'request';
import {
IExecuteFunctions,
IHookFunctions,
ILoadOptionsFunctions,
IExecuteSingleFunctions
} from 'n8n-core';
export async function mailchimpApiRequest(this: IHookFunctions | IExecuteFunctions | IExecuteSingleFunctions | ILoadOptionsFunctions, endpoint: string, method: string, body: any = {}, headers?: object): Promise<any> { // tslint:disable-line:no-any
2019-11-12 12:48:45 -08:00
const credentials = this.getCredentials('mailchimpApi');
if (credentials === undefined) {
throw new Error('No credentials got returned!');
}
const headerWithAuthentication = Object.assign({}, headers, { Authorization: `apikey ${credentials.apiKey}` });
if (!(credentials.apiKey as string).includes('-')) {
throw new Error('The API key is not valid!');
}
const datacenter = (credentials.apiKey as string).split('-').pop();
const host = 'api.mailchimp.com/3.0';
2019-11-12 12:48:45 -08:00
const options: OptionsWithUri = {
headers: headerWithAuthentication,
method,
uri: `https://${datacenter}.${host}${endpoint}`,
json: true,
2019-11-12 12:48:45 -08:00
};
if (Object.keys(body).length !== 0) {
options.body = body;
}
try {
return await this.helpers.request!(options);
} catch (error) {
const errorMessage = error.response.body.message || error.response.body.Message;
if (errorMessage !== undefined) {
throw errorMessage;
}
throw error.response.body;
}
}
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;
}