From 3293e6207f0d89929ea5892a445761bbce904eb2 Mon Sep 17 00:00:00 2001 From: Ricardo Espinoza Date: Sun, 7 Feb 2021 11:38:37 -0500 Subject: [PATCH] :sparkles: Add Stackby Node (#1414) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 🎉 Initial commit for stackby nodes * 👕 Adding values into package.json * :zap: Improvements to #1389 * :zap: Minor improvements to Stackby-Node * :shirt: Fix lint issue Co-authored-by: Smit Parmar <16ce061@charusat.edu.in> Co-authored-by: Smit Parmar <30971669+smituparmar@users.noreply.github.com> Co-authored-by: Jan Oberhauser --- .../credentials/StackbyApi.credentials.ts | 18 ++ .../nodes/Stackby/GenericFunction.ts | 108 +++++++ .../nodes-base/nodes/Stackby/Stackby.node.ts | 279 ++++++++++++++++++ packages/nodes-base/nodes/Stackby/stackby.png | Bin 0 -> 4155 bytes packages/nodes-base/package.json | 4 +- 5 files changed, 408 insertions(+), 1 deletion(-) create mode 100644 packages/nodes-base/credentials/StackbyApi.credentials.ts create mode 100644 packages/nodes-base/nodes/Stackby/GenericFunction.ts create mode 100644 packages/nodes-base/nodes/Stackby/Stackby.node.ts create mode 100644 packages/nodes-base/nodes/Stackby/stackby.png 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 0000000000000000000000000000000000000000..5f3937912cbcf7ad0ff22b14039972d5673288fa GIT binary patch literal 4155 zcmZ`+XEfW7_x>bS%xY^EB~^-s2Cdp#jh0YayQn>D#fXYoiYl!TwN+EI_9j+aqxPm& zYO9eLwa3r*<^RS1+;i`9?mg#u-rVQKy-~V4>hv@>XaE49*VIsbdWo|CC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NL_oa&ZxN8<=Mx45h6_WWBZ_QHRFNLSshd>C%&Dgr-BE{qDqAblm(_KJmm6o+MF3yRU%Tpnb=VRX&Iw<>_kYxDu zA)U{h3`Kt$jsUb z^}a|OHwmu>k+p39Asc{c7GyXrX(bJe7uQecGNf?WH)G4TFlGu@klxQKRh?Ah+E(-mmEkHdR2gv6xRy*hO& ztor+RF?JFHemjc@dTO3yo)zq&_yOm?-ZOpWl9=t2I#6hmX)kFnBp%%vT&M)Y`wX%K zp#wGRn<7oh&5`qugp0U`+v&hQ-=Y=uE2hP@5H%!Db{z=8yZhYh&CvcP`+VC!i@${( zfkXauC02&|NfD=CZ&BGu7R=9q5&ZbbI}F~aHjVXr2$LO`qqVGakAFzn`Cn&CqI zN)Ii=B|R@cE~k4#t>X1L{oK;uO>BsFRY`^H8S>LZej*h{gYNl`t#xrFTle?Jj=#Nm zUwSes;wu}`PmE2tOLKK<&ONiOrR1v%DU|FGD*0d>)i<8*oR*OK9IeXUl_O^v;#0dI z>g2C*D2w))&h>q_f}FO8T2V8SsBBF0ch{qfoUfxUM7JPTkm=>I@fz2vQn$51XUevz z4MRtn0y}ptJNfL^ew-4}Y`P=y!d0iR)5)lam|fgZn_o1e_?@O`>xsu)`4sdweo!l? zH2i8ZRs$kT5BA$cH{e<_j4Dg`jfeFn&CWNgd?G2@s&KYoXee2(U8J~dp!{tZP%~+& z@7pK6zWA$+IUM?so&}OXB2C)OSBMte_pKsP|&*fbd?kg;W!$b;M&347-nP=#p0<|&h{44~ zh2f&YVp0ZhacNOeX|eml@CVXxI0&@|{yzlQS2m7z{{KJ0{mzr7O9G&&rlVS{Y#I7L Dh`!)2 literal 0 HcmV?d00001 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