n8n/packages/nodes-base/nodes/Airtable/AirtableTrigger.node.ts

184 lines
5 KiB
TypeScript
Raw Normal View History

2020-11-06 17:18:10 -08:00
import {
IPollFunctions,
} from 'n8n-core';
import {
IDataObject,
INodeExecutionData,
INodeType,
INodeTypeDescription,
: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-11-06 17:18:10 -08:00
} from 'n8n-workflow';
import {
apiRequestAllItems,
downloadRecordAttachments,
2020-11-06 17:18:10 -08:00
} from './GenericFunctions';
import * as moment from 'moment';
export class AirtableTrigger implements INodeType {
description: INodeTypeDescription = {
displayName: 'Airtable Trigger',
name: 'airtableTrigger',
2020-11-25 05:09:29 -08:00
icon: 'file:airtable.svg',
2020-11-06 17:18:10 -08:00
group: ['trigger'],
version: 1,
description: 'Starts the workflow when Airtable events occur',
subtitle: '={{$parameter["event"]}}',
defaults: {
name: 'Airtable Trigger',
},
credentials: [
{
name: 'airtableApi',
required: true,
},
],
polling: true,
inputs: [],
outputs: ['main'],
properties: [
{
displayName: 'Base ID',
name: 'baseId',
type: 'string',
default: '',
required: true,
2020-11-10 13:40:44 -08:00
description: 'The ID of this base.',
2020-11-06 17:18:10 -08:00
},
{
displayName: 'Table ID',
2020-11-06 17:18:10 -08:00
name: 'tableId',
type: 'string',
default: '',
description: 'The ID of the table to access.',
2020-11-06 17:18:10 -08:00
required: true,
2020-11-10 13:40:44 -08:00
},
{
2020-11-06 17:18:10 -08:00
displayName: 'Trigger Field',
name: 'triggerField',
type: 'string',
default: '',
description: `A Created Time or Last Modified Time field that will be used to sort records. If you do not have a Created Time or Last Modified Time field in your schema, please create one, because without this field trigger will not work correctly.`,
2020-11-06 17:18:10 -08:00
required: true,
},
{
displayName: 'Download Attachments',
name: 'downloadAttachments',
type: 'boolean',
default: false,
description: `When set to true the attachment fields define in 'Download Fields' will be downloaded.`,
},
{
displayName: 'Download Fields',
name: 'downloadFieldNames',
type: 'string',
required: true,
displayOptions: {
show: {
downloadAttachments: [
true,
],
},
},
default: '',
description: `Name of the fields of type 'attachment' that should be downloaded. Multiple ones can be defined separated by comma. Case sensitive.`,
},
2020-11-06 17:18:10 -08:00
{
displayName: 'Additional Fields',
name: 'additionalFields',
type: 'collection',
placeholder: 'Add Field',
default: {},
options: [
{
displayName: 'Fields',
name: 'fields',
type: 'string',
default: '',
description: `Fields to be included in the response. Multiple ones can be set separated by comma. Example: <code>name, id</code>. By default just the trigger field will be included.`,
2020-11-06 17:18:10 -08:00
},
{
displayName: 'Formula',
name: 'formula',
type: 'string',
default: '',
description: `Formulas may involve functions, numeric operations, logical operations, and text operations that operate on fields. More info <a href="https://support.airtable.com/hc/en-us/articles/203255215-Formula-Field-Reference">here</a>.`,
2020-11-06 17:18:10 -08:00
},
{
displayName: 'View ID',
name: 'viewId',
type: 'string',
default: '',
description: 'The name or ID of a view in the table. If set, only the records in that view will be returned.',
2020-11-06 17:18:10 -08:00
},
],
},
],
};
async poll(this: IPollFunctions): Promise<INodeExecutionData[][] | null> {
const downloadAttachments = this.getNodeParameter('downloadAttachments', 0) as boolean;
2020-11-06 17:18:10 -08:00
const webhookData = this.getWorkflowStaticData('node');
const qs: IDataObject = {};
const additionalFields = this.getNodeParameter('additionalFields') as IDataObject;
const base = this.getNodeParameter('baseId') as string;
const table = this.getNodeParameter('tableId') as string;
const triggerField = this.getNodeParameter('triggerField') as string;
const endpoint = `${base}/${table}`;
const now = moment().utc().format();
const startDate = webhookData.lastTimeChecked as string || now;
const endDate = now;
if (additionalFields.viewId) {
qs.view = additionalFields.viewId;
}
if (additionalFields.fields) {
qs['fields[]'] = (additionalFields.fields as string).split(',');
}
qs.filterByFormula = `IS_AFTER({${triggerField}}, DATETIME_PARSE("${startDate}", "YYYY-MM-DD HH:mm:ss"))`;
if (additionalFields.formula) {
qs.filterByFormula = `AND(${qs.filterByFormula}, ${additionalFields.formula})`;
}
if (this.getMode() === 'manual') {
delete qs.filterByFormula;
qs.maxRecords = 1;
}
2020-11-06 17:18:10 -08:00
const { records } = await apiRequestAllItems.call(this, 'GET', endpoint, {}, qs);
webhookData.lastTimeChecked = endDate;
if (Array.isArray(records) && records.length) {
if (this.getMode() === 'manual' && records[0].fields[triggerField] === undefined) {
: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
throw new NodeOperationError(this.getNode(), `The Field "${triggerField}" does not exist.`);
}
if (downloadAttachments === true) {
const downloadFieldNames = (this.getNodeParameter('downloadFieldNames', 0) as string).split(',');
const data = await downloadRecordAttachments.call(this, records, downloadFieldNames);
return [data];
}
2020-11-06 17:18:10 -08:00
return [this.helpers.returnJsonArray(records)];
}
return null;
}
}