n8n/packages/nodes-base/nodes/CustomerIo/GenericFunctions.ts
agobrech 82a254a8d9
feat(Customer.io Node): Add support for tracking API region selection (#3378)
* support for customer.io tracking api endpoint region selection

If your account is based in our EU region use the EU endpoints (track-eu.customer.io) for US (other than EU) tracking endpoints (track.customer.io).

* Changed name to keep constistency with other nodes

* Switched to credentials injection

* Add throwing error when unknow way of authenticating

* Fixed url for http request

* Add hint to region field about being omited with http node

* Fix bug for credentials working with http node

* Improve IF by deduplicating code

Co-authored-by: h4ux <alon@h4ux.com>
Co-authored-by: Omar Ajoue <krynble@gmail.com>
2022-07-10 12:06:20 +03:00

66 lines
1.7 KiB
TypeScript

import {
IExecuteFunctions,
IHookFunctions,
ILoadOptionsFunctions,
} from 'n8n-core';
import {
OptionsWithUri,
} from 'request';
import {
IDataObject, IHttpRequestMethods, IHttpRequestOptions, NodeApiError, NodeOperationError,
} from 'n8n-workflow';
import {
get,
} from 'lodash';
export async function customerIoApiRequest(this: IHookFunctions | IExecuteFunctions | ILoadOptionsFunctions, method: string, endpoint: string, body: object, baseApi?: string, query?: IDataObject): Promise<any> { // tslint:disable-line:no-any
const credentials = await this.getCredentials('customerIoApi');
query = query || {};
const options: IHttpRequestOptions = {
headers: {
'Content-Type': 'application/json',
},
method: method as IHttpRequestMethods,
body,
url: '',
json: true,
};
if (baseApi === 'tracking') {
const region = credentials.region;
options.url = `https://${region}/api/v1${endpoint}`;
} else if (baseApi === 'api') {
options.url = `https://api.customer.io/v1/api${endpoint}`;
} else if (baseApi === 'beta') {
options.url = `https://beta-api.customer.io/v1/api${endpoint}`;
}
try {
return await this.helpers.requestWithAuthentication.call(this, 'customerIoApi' ,options );
} catch (error) {
throw new NodeApiError(this.getNode(), error);
}
}
export function eventExists(currentEvents: string[], webhookEvents: IDataObject) {
for (const currentEvent of currentEvents) {
if (get(webhookEvents, `${currentEvent.split('.')[0]}.${currentEvent.split('.')[1]}`) !== true) {
return false;
}
}
return true;
}
export function validateJSON(json: string | undefined): any { // tslint:disable-line:no-any
let result;
try {
result = JSON.parse(json!);
} catch (exception) {
result = undefined;
}
return result;
}