diff --git a/packages/nodes-base/credentials/StackbyApi.credentials.ts b/packages/nodes-base/credentials/StackbyApi.credentials.ts new file mode 100644 index 000000000..de4ad8f2a --- /dev/null +++ b/packages/nodes-base/credentials/StackbyApi.credentials.ts @@ -0,0 +1,18 @@ +import { + ICredentialType, + NodePropertyTypes, +} from 'n8n-workflow'; + +export class StackbyApi implements ICredentialType { + name = 'stackbyApi'; + displayName = 'Stackby API'; + documentationUrl = 'stackby'; + properties = [ + { + displayName: 'API Key', + name: 'apiKey', + type: 'string' as NodePropertyTypes, + default: '', + }, + ]; +} diff --git a/packages/nodes-base/nodes/Stackby/GenericFunction.ts b/packages/nodes-base/nodes/Stackby/GenericFunction.ts new file mode 100644 index 000000000..05c11abdc --- /dev/null +++ b/packages/nodes-base/nodes/Stackby/GenericFunction.ts @@ -0,0 +1,108 @@ +import { + IExecuteFunctions, + IHookFunctions, + ILoadOptionsFunctions, +} from 'n8n-core'; + +import { + OptionsWithUri, +} from 'request'; + +import { + IDataObject, + IPollFunctions, +} from 'n8n-workflow'; + +/** + * Make an API request to Airtable + * + * @param {IHookFunctions} this + * @param {string} method + * @param {string} url + * @param {object} body + * @returns {Promise} + */ +export async function apiRequest(this: IHookFunctions | IExecuteFunctions | ILoadOptionsFunctions | IPollFunctions, method: string, endpoint: string, body: IDataObject, query?: IDataObject, uri?: string, option: IDataObject = {}): Promise { // tslint:disable-line:no-any + const credentials = this.getCredentials('stackbyApi') as IDataObject; + + const options: OptionsWithUri = { + headers: { + 'api-key': credentials.apiKey, + 'Content-Type': 'application/json', + }, + method, + body, + qs: query, + uri: uri || `https://stackby.com/api/betav1${endpoint}`, + json: true, + }; + + if (Object.keys(option).length !== 0) { + Object.assign(options, option); + } + + if (Object.keys(body).length === 0) { + delete options.body; + } + + try { + return await this.helpers.request!(options); + + } catch (error) { + if (error.statusCode === 401) { + // Return a clear error + throw new Error('The stackby credentials are not valid!'); + } + + if (error.response && error.response.body && error.response.body.error) { + // Try to return the error prettier + const message = error.response.body.error; + + throw new Error(`Stackby error response [${error.statusCode}]: ${message}`); + } + + // Expected error data did not get returned so rhow the actual error + throw error; + } +} + +/** + * Make an API request to paginated Airtable endpoint + * and return all results + * + * @export + * @param {(IHookFunctions | IExecuteFunctions)} this + * @param {string} method + * @param {string} endpoint + * @param {IDataObject} body + * @param {IDataObject} [query] + * @returns {Promise} + */ +export async function apiRequestAllItems(this: IHookFunctions | IExecuteFunctions | IPollFunctions, method: string, endpoint: string, body: IDataObject = {}, query: IDataObject = {}): Promise { // tslint:disable-line:no-any + + query.maxrecord = 100; + + query.offset = 0; + + const returnData: IDataObject[] = []; + + let responseData; + + do { + responseData = await apiRequest.call(this, method, endpoint, body, query); + returnData.push.apply(returnData, responseData); + query.offset += query.maxrecord; + + } while ( + responseData.length !== 0 + ); + + return returnData; +} + +export interface IRecord { + field: { + [key: string]: string + }; +} + diff --git a/packages/nodes-base/nodes/Stackby/Stackby.node.ts b/packages/nodes-base/nodes/Stackby/Stackby.node.ts new file mode 100644 index 000000000..cd31dc9d5 --- /dev/null +++ b/packages/nodes-base/nodes/Stackby/Stackby.node.ts @@ -0,0 +1,279 @@ +import { + IExecuteFunctions, +} from 'n8n-core'; + +import { + IDataObject, + INodeExecutionData, + INodeType, + INodeTypeDescription, +} 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: 'Consume Stackby REST API', + 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,
only the records in that view will be returned. The records
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 { + 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 Error(`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)]; + } +} diff --git a/packages/nodes-base/nodes/Stackby/stackby.png b/packages/nodes-base/nodes/Stackby/stackby.png new file mode 100644 index 000000000..5f3937912 Binary files /dev/null and b/packages/nodes-base/nodes/Stackby/stackby.png differ diff --git a/packages/nodes-base/package.json b/packages/nodes-base/package.json index 4fe62af63..851e13e54 100644 --- a/packages/nodes-base/package.json +++ b/packages/nodes-base/package.json @@ -199,6 +199,7 @@ "dist/credentials/Snowflake.credentials.js", "dist/credentials/Smtp.credentials.js", "dist/credentials/SpotifyOAuth2Api.credentials.js", + "dist/credentials/StackbyApi.credentials.js", "dist/credentials/StravaOAuth2Api.credentials.js", "dist/credentials/StripeApi.credentials.js", "dist/credentials/Sftp.credentials.js", @@ -449,6 +450,7 @@ "dist/nodes/Spontit/Spontit.node.js", "dist/nodes/Spotify/Spotify.node.js", "dist/nodes/SpreadsheetFile.node.js", + "dist/nodes/Stackby/Stackby.node.js", "dist/nodes/SseTrigger.node.js", "dist/nodes/Start.node.js", "dist/nodes/Storyblok/Storyblok.node.js", @@ -598,4 +600,4 @@ "json" ] } -} +} \ No newline at end of file