Improvements

This commit is contained in:
ricardo 2020-08-03 17:11:57 -04:00
parent a443bf797d
commit 4b02ed2f37
2 changed files with 98 additions and 83 deletions

View file

@ -2,16 +2,28 @@ import {
IHookFunctions, IHookFunctions,
IWebhookFunctions, IWebhookFunctions,
} from 'n8n-core'; } from 'n8n-core';
import { import {
INodeTypeDescription, INodeTypeDescription,
INodeType, INodeType,
IDataObject, IDataObject,
IWebhookResponseData, IWebhookResponseData,
} from 'n8n-workflow'; } from 'n8n-workflow';
import { import {
apiRequest, apiRequest,
eventExists,
} from './GenericFunctions'; } from './GenericFunctions';
interface IEvent{
customer?: IDataObject;
email?: IDataObject;
push?: IDataObject;
slack?: IDataObject;
sms?: IDataObject;
webhook?: IDataObject;
}
export class CustomerIoTrigger implements INodeType { export class CustomerIoTrigger implements INodeType {
description: INodeTypeDescription = { description: INodeTypeDescription = {
displayName: 'Customer.io Trigger', displayName: 'Customer.io Trigger',
@ -19,10 +31,9 @@ export class CustomerIoTrigger implements INodeType {
group: ['trigger'], group: ['trigger'],
icon: 'file:customer.Io.png', icon: 'file:customer.Io.png',
version: 1, version: 1,
subtitle: '=Updates: {{$parameter["updates"].join(", ")}}', description: 'Starts the workflow on a Customer.io update. (Beta)',
description: 'Starts the workflow on a Customer.io update.',
defaults: { defaults: {
name: 'CustomerDotIO Trigger', name: 'Customer.io Trigger',
color: '#00FF00', color: '#00FF00',
}, },
inputs: [], inputs: [],
@ -31,7 +42,7 @@ export class CustomerIoTrigger implements INodeType {
{ {
name: 'customerIoApi', name: 'customerIoApi',
required: true, required: true,
} },
], ],
webhooks: [ webhooks: [
{ {
@ -176,40 +187,39 @@ export class CustomerIoTrigger implements INodeType {
}, },
{ {
name: 'SMS attempted', name: 'SMS attempted',
value: 'slack.attempted', value: 'sms.attempted',
description: 'Whether the webhook is triggered when a list member unsubscribes.', description: 'Whether the webhook is triggered when a list member unsubscribes.',
}, },
{ {
name: 'SMS bounced', name: 'SMS bounced',
value: 'slack.bounced', value: 'sms.bounced',
description: 'Whether the webhook is triggered when a list member unsubscribes.', description: 'Whether the webhook is triggered when a list member unsubscribes.',
}, },
{ {
name: 'SMS clicked', name: 'SMS clicked',
value: 'slack.clicked', value: 'sms.clicked',
description: 'Whether the webhook is triggered when a list member unsubscribes.', description: 'Whether the webhook is triggered when a list member unsubscribes.',
}, },
{ {
name: 'SMS delivered', name: 'SMS delivered',
value: 'slack.delivered', value: 'sms.delivered',
description: 'Whether the webhook is triggered when a list member unsubscribes.', description: 'Whether the webhook is triggered when a list member unsubscribes.',
}, },
{ {
name: 'SMS drafted', name: 'SMS drafted',
value: 'slack.drafted', value: 'sms.drafted',
description: 'Whether the webhook is triggered when a list member unsubscribes.', description: 'Whether the webhook is triggered when a list member unsubscribes.',
}, },
{ {
name: 'SMS failed', name: 'SMS failed',
value: 'slack.failed', value: 'sms.failed',
description: 'Whether the webhook is triggered when a list member unsubscribes.', description: 'Whether the webhook is triggered when a list member unsubscribes.',
}, },
{ {
name: 'SMS sent', name: 'SMS sent',
value: 'slack.sent', value: 'sms.sent',
description: 'Whether the webhook is triggered when a list member unsubscribes.', description: 'Whether the webhook is triggered when a list member unsubscribes.',
}, },
], ],
}, },
], ],
@ -218,72 +228,77 @@ export class CustomerIoTrigger implements INodeType {
webhookMethods = { webhookMethods = {
default: { default: {
async checkExists(this: IHookFunctions): Promise<boolean> { async checkExists(this: IHookFunctions): Promise<boolean> {
const webhookUrl = this.getNodeWebhookUrl('default');
const webhookData = this.getWorkflowStaticData('node'); const webhookData = this.getWorkflowStaticData('node');
console.log("in checkexists function")
if (webhookData.webhookId === undefined) { const currentEvents = this.getNodeParameter('events', []) as string[];
// No webhook id is set so no webhook can exist
return false; const endpoint = '/reporting_webhooks';
}
const endpoint = `/reporting_webhooks/${webhookData.webhookId}`; let { reporting_webhooks: webhooks } = await apiRequest.call(this, 'GET', endpoint, {});
try {
await apiRequest.call(this, 'GET', endpoint, {}); if (webhooks === null) {
} catch (err) { webhooks = [];
if (err.statusCode === 404) {
return false;
}
throw new Error(`Customer.io Error: ${err}`);
} }
return true; for (const webhook of webhooks) {
if (webhook.endpoint === webhookUrl &&
eventExists(currentEvents, webhook.events)) {
webhookData.webhookId = webhook.id;
return true;
}
}
return false;
}, },
async create(this: IHookFunctions): Promise<boolean> { async create(this: IHookFunctions): Promise<boolean> {
let webhook; let webhook;
const webhookUrl = this.getNodeWebhookUrl('default'); const webhookUrl = this.getNodeWebhookUrl('default');
const events = this.getNodeParameter('events', []) as string[]; const events = this.getNodeParameter('events', []) as string[];
const endpoint1 = '/reporting_webhooks'; const endpoint = '/reporting_webhooks';
const data: IEvent = {
customer: {},
email: {},
push: {},
slack: {},
sms: {},
webhook: {},
};
for (const event of events) { for (const event of events) {
var obj = event.split('.'); const option = event.split('.')[1];
if (event.startsWith('customer')) {
// var obj2 = JSON.stringify(obj); data.customer![option] = true;
// var key = obj[0]; //push }
// var val = JSON.stringify(obj[1]); //attempted if (event.startsWith('email')) {
data.email![option] = true;
// var obj1: { obj2: boolean; } = { obj2: true }; //{'attempted':true} }
if (event.startsWith('push')) {
data.push![option] = true;
}
if (event.startsWith('slack')) {
data.slack![option] = true;
}
if (event.startsWith('sms')) {
data.sms![option] = true;
}
if (event.startsWith('webhook')) {
data.webhook![option] = true;
}
} }
const body = { const body = {
endpoint: webhookUrl, endpoint: webhookUrl,
// events: events.reduce((object, currentValue) => { events: data,
// // @ts-ignore
// var obj = currentValue.split('.');
// //object[currentValue] = true;
// return object;
// }, {}),
"events": {
"customer": {
"subscribed": false,
"unsubscribed": true
},
},
}; };
console.log(body);
try { webhook = await apiRequest.call(this, 'POST', endpoint, body);
webhook = await apiRequest.call(this, 'POST', endpoint1, body);
} catch (e) {
throw e;
}
if (webhook.id === undefined) {
return false;
}
const webhookData = this.getWorkflowStaticData('node'); const webhookData = this.getWorkflowStaticData('node');
webhookData.webhookId = webhook.id as string; webhookData.webhookId = webhook.id as string;
webhookData.events = events;
return true; return true;
}, },
async delete(this: IHookFunctions): Promise<boolean> { async delete(this: IHookFunctions): Promise<boolean> {
const webhookData = this.getWorkflowStaticData('node'); const webhookData = this.getWorkflowStaticData('node');
@ -291,40 +306,23 @@ export class CustomerIoTrigger implements INodeType {
if (webhookData.webhookId !== undefined) { if (webhookData.webhookId !== undefined) {
const endpoint = `/reporting_webhooks/${webhookData.webhookId}`; const endpoint = `/reporting_webhooks/${webhookData.webhookId}`;
try { try {
await apiRequest.call(this, endpoint, 'DELETE', {}); await apiRequest.call(this, 'DELETE', endpoint, {});
} catch (e) { } catch (e) {
return false; return false;
} }
delete webhookData.webhookId; delete webhookData.webhookId;
delete webhookData.events;
} }
return true; return true;
}, },
} }
}; };
async webhook(this: IWebhookFunctions): Promise<IWebhookResponseData> { async webhook(this: IWebhookFunctions): Promise<IWebhookResponseData> {
const bodyData = this.getBodyData(); const bodyData = this.getBodyData();
const webhookData = this.getWorkflowStaticData('node') as IDataObject;
const req = this.getRequestObject();
if (req.body.id !== webhookData.id) {
return {};
}
// @ts-ignore
if (!webhookData.events.includes(req.body.type)
// @ts-ignore
&& !webhookData.sources.includes(req.body.type)) {
return {};
}
return { return {
workflowData: [ workflowData: [
this.helpers.returnJsonArray([bodyData]) this.helpers.returnJsonArray(bodyData)
], ],
}; };
} }
} }

View file

@ -4,8 +4,17 @@ import {
ILoadOptionsFunctions, ILoadOptionsFunctions,
} from 'n8n-core'; } from 'n8n-core';
import { OptionsWithUri } from 'request'; import {
import { IDataObject } from 'n8n-workflow'; OptionsWithUri,
} from 'request';
import {
IDataObject,
} from 'n8n-workflow';
import {
get,
} from 'lodash';
export async function apiRequest(this: IHookFunctions | IExecuteFunctions | ILoadOptionsFunctions, method: string, endpoint: string, body: object, query?: IDataObject): Promise<any> { // tslint:disable-line:no-any export async function apiRequest(this: IHookFunctions | IExecuteFunctions | ILoadOptionsFunctions, method: string, endpoint: string, body: object, query?: IDataObject): Promise<any> { // tslint:disable-line:no-any
const credentials = this.getCredentials('customerIoApi'); const credentials = this.getCredentials('customerIoApi');
@ -27,7 +36,6 @@ export async function apiRequest(this: IHookFunctions | IExecuteFunctions | ILoa
uri: `https://beta-api.customer.io/v1/api${endpoint}`, uri: `https://beta-api.customer.io/v1/api${endpoint}`,
json: true, json: true,
}; };
console.log(options);
try { try {
return await this.helpers.request!(options); return await this.helpers.request!(options);
} catch (error) { } catch (error) {
@ -46,3 +54,12 @@ export async function apiRequest(this: IHookFunctions | IExecuteFunctions | ILoa
throw error; throw 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;
}