n8n/packages/nodes-base/nodes/Stackby/Stackby.node.ts
Iván Ovejero 1d27a9e87e
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

* 🚧 create basic setup NodeError

* 🚧 add httpCodes

* 🚧 add path priolist

* 🚧 handle statusCode in error, adjust interfaces

* 🚧 fixing type issues w/Ivan

* 🚧 add error exploration

* 👔 fix linter issues

* 🔧 improve object check

* 🚧 remove path passing from NodeApiError

* 🚧 add multi error + refactor findProperty method

* 👔 allow any

* 🔧 handle multi error message callback

*  change return type of callback

*  add customCallback to MultiError

* 🚧 refactor to use INode

* 🔨 handle arrays, continue search after first null property found

* 🚫 refactor method access

* 🚧 setup NodeErrorView

*  change timestamp to Date.now

* 📚 Add documentation for methods and constants

* 🚧 change message setting

* 🚚 move NodeErrors to workflow

*  add new ErrorView for Nodes

* 🎨 improve error notification

* 🎨 refactor interfaces

*  add WorkflowOperationError, refactor error throwing

* 👕 fix linter issues

* 🎨 rename param

* 🐛 fix handling normal errors

*  add usage of NodeApiError

* 🎨 fix throw new error instead of constructor

* 🎨 remove unnecessary code/comments

* 🎨 adjusted spacing + updated status messages

* 🎨 fix tab indentation

*  Replace current errors with custom errors (#1576)

*  Introduce NodeApiError in catch blocks

*  Introduce NodeOperationError in nodes

*  Add missing errors and remove incompatible

*  Fix NodeOperationError in incompatible nodes

* 🔧 Adjust error handling in missed nodes

PayPal, FileMaker, Reddit, Taiga and Facebook Graph API nodes

* 🔨 Adjust Strava Trigger node error handling

* 🔨 Adjust AWS nodes error handling

* 🔨 Remove duplicate instantiation of NodeApiError

* 🐛 fix strava trigger node error handling

* Add XML parsing to NodeApiError constructor (#1633)

* 🐛 Remove type annotation from catch variable

*  Add XML parsing to NodeApiError

*  Simplify error handling in Rekognition node

*  Pass in XML flag in generic functions

* 🔥 Remove try/catch wrappers at call sites

* 🔨 Refactor setting description from XML

* 🔨 Refactor let to const in resource loaders

*  Find property in parsed XML

*  Change let to const

* 🔥 Remove unneeded try/catch block

* 👕 Fix linting issues

* 🐛 Fix errors from merge conflict resolution

*  Add custom errors to latest contributions

* 👕 Fix linting issues

*  Refactor MongoDB helpers for custom errors

* 🐛 Correct custom error type

*  Apply feedback to A nodes

*  Apply feedback to missed A node

*  Apply feedback to B-D nodes

*  Apply feedback to E-F nodes

*  Apply feedback to G nodes

*  Apply feedback to H-L nodes

*  Apply feedback to M nodes

*  Apply feedback to P nodes

*  Apply feedback to R nodes

*  Apply feedback to S nodes

*  Apply feedback to T nodes

*  Apply feedback to V-Z nodes

*  Add HTTP code to iterable node error

* 🔨 Standardize e as error

* 🔨 Standardize err as error

*  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 18:33:36 +02:00

281 lines
7.1 KiB
TypeScript

import {
IExecuteFunctions,
} from 'n8n-core';
import {
IDataObject,
INodeExecutionData,
INodeType,
INodeTypeDescription,
NodeOperationError,
} from 'n8n-workflow';
import {
apiRequest,
apiRequestAllItems,
IRecord,
} from './GenericFunction';
export class Stackby implements INodeType {
description: INodeTypeDescription = {
displayName: 'Stackby',
name: 'stackby',
icon: 'file:stackby.png',
group: ['transform'],
version: 1,
description: 'Read, Write, and Delete Data in Stackby',
defaults: {
name: 'Stackby',
color: '#772244',
},
inputs: ['main'],
outputs: ['main'],
credentials: [
{
name: 'stackbyApi',
required: true,
},
],
properties: [
{
displayName: 'Operation',
name: 'operation',
type: 'options',
options: [
{
name: 'Append',
value: 'append',
},
{
name: 'Delete',
value: 'delete',
},
{
name: 'List',
value: 'list',
},
{
name: 'Read',
value: 'read',
},
],
default: 'append',
placeholder: 'Action to perform',
},
// ----------------------------------
// All
// ----------------------------------
{
displayName: 'Stack ID',
name: 'stackId',
type: 'string',
default: '',
required: true,
description: 'The ID of the stack to access.',
},
{
displayName: 'Table',
name: 'table',
type: 'string',
default: '',
placeholder: 'Stories',
required: true,
description: 'Enter Table Name',
},
// ----------------------------------
// read
// ----------------------------------
{
displayName: 'ID',
name: 'id',
type: 'string',
displayOptions: {
show: {
operation: [
'read',
'delete',
],
},
},
default: '',
required: true,
description: 'ID of the record to return.',
},
// ----------------------------------
// list
// ----------------------------------
{
displayName: 'Return All',
name: 'returnAll',
type: 'boolean',
displayOptions: {
show: {
operation: [
'list',
],
},
},
default: true,
description: 'If all results should be returned or only up to a given limit.',
},
{
displayName: 'Limit',
name: 'limit',
type: 'number',
displayOptions: {
show: {
'operation': [
'list',
],
'returnAll': [
false,
],
},
},
typeOptions: {
minValue: 1,
maxValue: 1000,
},
default: 1000,
description: 'Number of results to return.',
},
{
displayName: 'Additional Fields',
name: 'additionalFields',
type: 'collection',
displayOptions: {
show: {
operation: [
'list',
],
},
},
default: {},
placeholder: 'Add Field',
options: [
{
displayName: 'View',
name: 'view',
type: 'string',
default: '',
placeholder: 'All Stories',
description: 'The name or ID of a view in the Stories table. If set,<br />only the records in that view will be returned. The records<br />will be sorted according to the order of the view.',
},
],
},
// ----------------------------------
// append
// ----------------------------------
{
displayName: 'Columns',
name: 'columns',
type: 'string',
displayOptions: {
show: {
operation: [
'append',
],
},
},
default: '',
required: true,
placeholder: 'id,name,description',
description: 'Comma separated list of the properties which should used as columns for the new rows.',
},
],
};
async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> {
const items = this.getInputData();
const returnData: IDataObject[] = [];
const length = items.length as unknown as number;
let responseData;
const qs: IDataObject = {};
const operation = this.getNodeParameter('operation', 0) as string;
if (operation === 'read') {
for (let i = 0; i < length; i++) {
const stackId = this.getNodeParameter('stackId', i) as string;
const table = encodeURI(this.getNodeParameter('table', i) as string);
const rowIds = this.getNodeParameter('id', i) as string;
qs.rowIds = [rowIds];
responseData = await apiRequest.call(this, 'GET', `/rowlist/${stackId}/${table}`, {}, qs);
// tslint:disable-next-line: no-any
returnData.push.apply(returnData, responseData.map((data: any) => data.field));
}
}
if (operation === 'delete') {
for (let i = 0; i < length; i++) {
const stackId = this.getNodeParameter('stackId', i) as string;
const table = encodeURI(this.getNodeParameter('table', i) as string);
const rowIds = this.getNodeParameter('id', i) as string;
qs.rowIds = [rowIds];
responseData = await apiRequest.call(this, 'DELETE', `/rowdelete/${stackId}/${table}`, {}, qs);
responseData = responseData.records;
returnData.push.apply(returnData, responseData);
}
}
if (operation === 'append') {
const records: { [key: string]: IRecord[] } = {};
let key = '';
for (let i = 0; i < length; i++) {
const stackId = this.getNodeParameter('stackId', i) as string;
const table = encodeURI(this.getNodeParameter('table', i) as string);
const columns = this.getNodeParameter('columns', i) as string;
const columnList = columns.split(',').map(column => column.trim());
// tslint:disable-next-line: no-any
const record: { [key: string]: any } = {};
for (const column of columnList) {
if (items[i].json[column] === undefined) {
throw new NodeOperationError(this.getNode(), `Column ${column} does not exist on input`);
} else {
record[column] = items[i].json[column];
}
}
key = `${stackId}/${table}`;
if (records[key] === undefined) {
records[key] = [];
}
records[key].push({ field: record });
}
for (const key of Object.keys(records)) {
responseData = await apiRequest.call(this, 'POST', `/rowcreate/${key}`, { records: records[key] });
}
// tslint:disable-next-line: no-any
returnData.push.apply(returnData, responseData.map((data: any) => data.field));
}
if (operation === 'list') {
for (let i = 0; i < length; i++) {
const stackId = this.getNodeParameter('stackId', i) as string;
const table = encodeURI(this.getNodeParameter('table', i) as string);
const returnAll = this.getNodeParameter('returnAll', 0) as boolean;
const additionalFields = this.getNodeParameter('additionalFields', i, {}) as IDataObject;
if (additionalFields.view) {
qs.view = additionalFields.view;
}
if (returnAll === true) {
responseData = await apiRequestAllItems.call(this, 'GET', `/rowlist/${stackId}/${table}`, {}, qs);
} else {
qs.maxrecord = this.getNodeParameter('limit', 0) as number;
responseData = await apiRequest.call(this, 'GET', `/rowlist/${stackId}/${table}`, {}, qs);
}
// tslint:disable-next-line: no-any
returnData.push.apply(returnData, responseData.map((data: any) => data.field));
}
}
return [this.helpers.returnJsonArray(returnData)];
}
}