n8n/packages/nodes-base/nodes/Aws/AwsSnsTrigger.node.ts

283 lines
7.1 KiB
TypeScript
Raw Normal View History

import { IHookFunctions, IWebhookFunctions } from 'n8n-core';
2020-02-08 14:19:00 -08:00
import {
ILoadOptionsFunctions,
2022-11-28 03:27:20 -08:00
INodeListSearchItems,
INodeListSearchResult,
INodeType,
INodeTypeDescription,
IWebhookResponseData,
jsonParse,
: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
NodeOperationError,
2020-02-08 14:19:00 -08:00
} from 'n8n-workflow';
import { awsApiRequestSOAP } from './GenericFunctions';
2020-02-08 14:19:00 -08:00
import { get } from 'lodash';
2020-02-08 14:19:00 -08:00
export class AwsSnsTrigger implements INodeType {
description: INodeTypeDescription = {
displayName: 'AWS SNS Trigger',
subtitle: `={{$parameter["topic"].split(':')[5]}}`,
2020-02-09 18:27:06 -08:00
name: 'awsSnsTrigger',
icon: 'file:sns.svg',
2020-02-08 14:19:00 -08:00
group: ['trigger'],
version: 1,
description: 'Handle AWS SNS events via webhooks',
defaults: {
2020-02-09 18:27:06 -08:00
name: 'AWS-SNS-Trigger',
2020-02-08 14:19:00 -08:00
},
inputs: [],
outputs: ['main'],
credentials: [
{
name: 'aws',
required: true,
},
2020-02-08 14:19:00 -08:00
],
webhooks: [
{
name: 'default',
httpMethod: 'POST',
responseMode: 'onReceived',
path: 'webhook',
},
],
properties: [
{
2022-11-28 03:27:20 -08:00
displayName: 'Topic',
2020-02-08 14:19:00 -08:00
name: 'topic',
2022-11-28 03:27:20 -08:00
type: 'resourceLocator',
default: { mode: 'list', value: '' },
2020-02-08 14:19:00 -08:00
required: true,
2022-11-28 03:27:20 -08:00
modes: [
{
displayName: 'From List',
name: 'list',
type: 'list',
placeholder: 'Select a topic...',
typeOptions: {
searchListMethod: 'listTopics',
searchable: true,
},
},
{
displayName: 'By URL',
name: 'url',
type: 'string',
placeholder:
'https://us-east-1.console.aws.amazon.com/sns/v3/home?region=us-east-1#/topic/arn:aws:sns:us-east-1:777777777777:your_topic',
validation: [
{
type: 'regex',
properties: {
regex:
'https:\\/\\/[0-9a-zA-Z\\-_]+\\.console\\.aws\\.amazon\\.com\\/sns\\/v3\\/home\\?region\\=[0-9a-zA-Z\\-_]+\\#\\/topic\\/arn:aws:sns:[0-9a-zA-Z\\-_]+:[0-9]+:[0-9a-zA-Z\\-_]+(?:\\/.*|)',
errorMessage: 'Not a valid AWS SNS Topic URL',
},
},
],
extractValue: {
type: 'regex',
regex:
'https:\\/\\/[0-9a-zA-Z\\-_]+\\.console\\.aws\\.amazon\\.com\\/sns\\/v3\\/home\\?region\\=[0-9a-zA-Z\\-_]+\\#\\/topic\\/(arn:aws:sns:[0-9a-zA-Z\\-_]+:[0-9]+:[0-9a-zA-Z\\-_]+)(?:\\/.*|)',
},
},
{
displayName: 'ID',
name: 'id',
type: 'string',
validation: [
{
type: 'regex',
properties: {
regex: 'arn:aws:sns:[0-9a-zA-Z\\-_]+:[0-9]+:[0-9a-zA-Z\\-_]+',
errorMessage: 'Not a valid AWS SNS Topic ARN',
},
},
],
placeholder: 'arn:aws:sns:your-aws-region:777777777777:your_topic',
},
],
2020-02-08 14:19:00 -08:00
},
],
};
methods = {
2022-11-28 03:27:20 -08:00
listSearch: {
async listTopics(
this: ILoadOptionsFunctions,
filter?: string,
paginationToken?: string,
): Promise<INodeListSearchResult> {
const returnData: INodeListSearchItems[] = [];
const params = paginationToken ? `NextToken=${encodeURIComponent(paginationToken)}` : '';
const data = await awsApiRequestSOAP.call(
this,
'sns',
'GET',
'/?Action=ListTopics&' + params,
);
2020-02-08 14:19:00 -08:00
let topics = data.ListTopicsResponse.ListTopicsResult.Topics.member;
2022-11-28 03:27:20 -08:00
const nextToken = data.ListTopicsResponse.ListTopicsResult.NextToken;
if (nextToken) {
paginationToken = nextToken as string;
} else {
paginationToken = undefined;
}
2020-02-08 14:19:00 -08:00
if (!Array.isArray(topics)) {
topics = [topics];
}
for (const topic of topics) {
const topicArn = topic.TopicArn as string;
2022-11-28 03:27:20 -08:00
const arnParsed = topicArn.split(':');
const topicName = arnParsed[5];
const awsRegion = arnParsed[3];
if (filter && !topicName.includes(filter)) {
2022-11-28 03:27:20 -08:00
continue;
}
2020-02-08 14:19:00 -08:00
returnData.push({
name: topicName,
value: topicArn,
2022-11-28 03:27:20 -08:00
url: `https://${awsRegion}.console.aws.amazon.com/sns/v3/home?region=${awsRegion}#/topic/${topicArn}`,
2020-02-08 14:19:00 -08:00
});
}
2022-11-28 03:27:20 -08:00
return { results: returnData, paginationToken };
2020-10-22 06:46:03 -07:00
},
2020-02-08 14:19:00 -08:00
},
};
2022-11-28 03:27:20 -08:00
//@ts-expect-error because of webhook
2020-02-08 14:19:00 -08:00
webhookMethods = {
default: {
async checkExists(this: IHookFunctions): Promise<boolean> {
const webhookData = this.getWorkflowStaticData('node');
2022-11-28 03:27:20 -08:00
const topic = this.getNodeParameter('topic', undefined, {
extractValue: true,
}) as string;
2020-02-08 14:19:00 -08:00
if (webhookData.webhookId === undefined) {
return false;
}
const params = [`TopicArn=${topic}`, 'Version=2010-03-31'];
const data = await awsApiRequestSOAP.call(
this,
'sns',
'GET',
'/?Action=ListSubscriptionsByTopic&' + params.join('&'),
);
const subscriptions = get(
data,
'ListSubscriptionsByTopicResponse.ListSubscriptionsByTopicResult.Subscriptions',
);
if (!subscriptions || !subscriptions.member) {
return false;
}
let subscriptionMembers = subscriptions.member;
if (!Array.isArray(subscriptionMembers)) {
subscriptionMembers = [subscriptionMembers];
}
for (const subscription of subscriptionMembers) {
2020-02-08 14:19:00 -08:00
if (webhookData.webhookId === subscription.SubscriptionArn) {
return true;
}
}
return false;
},
async create(this: IHookFunctions): Promise<boolean> {
const webhookData = this.getWorkflowStaticData('node');
2020-02-09 18:27:06 -08:00
const webhookUrl = this.getNodeWebhookUrl('default') as string;
2022-11-28 03:27:20 -08:00
const topic = this.getNodeParameter('topic', undefined, {
extractValue: true,
}) as string;
2020-02-09 18:27:06 -08:00
if (webhookUrl.includes('%20')) {
throw new NodeOperationError(
this.getNode(),
'The name of the SNS Trigger Node is not allowed to contain any spaces!',
);
2020-02-09 18:27:06 -08:00
}
2020-02-08 14:19:00 -08:00
const params = [
`TopicArn=${topic}`,
`Endpoint=${webhookUrl}`,
`Protocol=${webhookUrl?.split(':')[0]}`,
'ReturnSubscriptionArn=true',
'Version=2010-03-31',
];
2020-02-09 18:27:06 -08:00
const { SubscribeResponse } = await awsApiRequestSOAP.call(
this,
'sns',
'GET',
'/?Action=Subscribe&' + params.join('&'),
);
2020-02-09 18:27:06 -08:00
webhookData.webhookId = SubscribeResponse.SubscribeResult.SubscriptionArn;
2020-02-08 14:19:00 -08:00
return true;
},
async delete(this: IHookFunctions): Promise<boolean> {
const webhookData = this.getWorkflowStaticData('node');
const params = [`SubscriptionArn=${webhookData.webhookId}`, 'Version=2010-03-31'];
2020-02-08 14:19:00 -08:00
try {
await awsApiRequestSOAP.call(
this,
'sns',
'GET',
'/?Action=Unsubscribe&' + params.join('&'),
);
} catch (error) {
2020-02-08 14:19:00 -08:00
return false;
}
delete webhookData.webhookId;
return true;
},
},
};
async webhook(this: IWebhookFunctions): Promise<IWebhookResponseData> {
const req = this.getRequestObject();
2022-11-28 03:27:20 -08:00
const topic = this.getNodeParameter('topic', undefined, {
extractValue: true,
}) as string;
2020-02-09 18:27:06 -08:00
const body = jsonParse<{ Type: string; TopicArn: string; Token: string }>(
req.rawBody.toString(),
);
2020-02-09 18:27:06 -08:00
if (body.Type === 'SubscriptionConfirmation' && body.TopicArn === topic) {
2020-02-09 18:27:06 -08:00
const { Token } = body;
const params = [`TopicArn=${topic}`, `Token=${Token}`, 'Version=2010-03-31'];
await awsApiRequestSOAP.call(
this,
'sns',
'GET',
'/?Action=ConfirmSubscription&' + params.join('&'),
);
2020-02-09 18:27:06 -08:00
return {
noWebhookResponse: true,
};
2020-02-08 14:19:00 -08:00
}
2020-02-09 18:27:06 -08:00
if (body.Type === 'UnsubscribeConfirmation') {
2020-02-08 14:19:00 -08:00
return {};
}
2020-02-09 18:27:06 -08:00
2020-02-08 14:19:00 -08:00
//TODO verify message signature
return {
workflowData: [this.helpers.returnJsonArray(body)],
2020-02-08 14:19:00 -08:00
};
}
}