n8n/packages/nodes-base/nodes/NocoDB/NocoDB.node.ts

382 lines
11 KiB
TypeScript
Raw Normal View History

refactor: Apply more `eslint-plugin-n8n-nodes-base` rules (#3624) * :arrow_up: Upgrade `eslint-plugin-n8n-nodes-base` * :package: Update `package-lock.json` * :wrench: Adjust renamed filesystem rules * :pencil2: Alphabetize ruleset * :zap: Categorize overrides * :zap: Set renamings in lint exceptions * :zap: Run baseline `lintfix` * :zap: Update linting scripts * :shirt: Apply `node-param-description-missing-from-dynamic-multi-options` * :shirt: Apply `cred-class-field-name-missing-oauth2` (#3627) * Rule working as intended * Removed comments * Move cred rule to different rule set * :shirt: Apply `node-param-array-type-assertion` * :shirt: Apply `node-dirname-against-convention` * Apply `cred-class-field-display-name-oauth2` (#3628) * Apply `node-execute-block-wrong-error-thrown` * Apply `node-class-description-display-name-unsuffixed-trigger-node` * Apply `node-class-description-name-unsuffixed-trigger-node` * Apply `cred-class-name-missing-oauth2-suffix` (#3636) * Rule working as intended, add exception to existing nodes * :shirt: Apply `cred-class-field-name-uppercase-first-char` (#3638) * :arrow_up: Upgrade to plugin version 1.2.28 * :package: Update `package-lock.json` * :shirt: Update lintings with 1.2.8 change * :shirt: Apply `cred-class-field-name-unsuffixed` * :shirt: Apply `cred-class-name-unsuffixed` * :shirt: Apply `node-class-description-credentials-name-unsuffixed` * :pencil2: Alphabetize rules * :heavy_minus_sign: Remove `nodelinter` package * :package: Update `package-lock.json` * :zap: Consolidate `lint` and `lintfix` scripts Co-authored-by: agobrech <45268029+agobrech@users.noreply.github.com> Co-authored-by: agobrech <ael.gobrecht@gmail.com>
2022-07-04 02:12:08 -07:00
/* eslint-disable n8n-nodes-base/node-filename-against-convention */
import {
IExecuteFunctions,
} from 'n8n-core';
import {
IBinaryData,
IDataObject,
INodeExecutionData,
INodeType,
INodeTypeDescription,
NodeApiError,
NodeOperationError,
} from 'n8n-workflow';
import {
apiRequest,
apiRequestAllItems,
downloadRecordAttachments,
} from './GenericFunctions';
import {
operationFields
} from './OperationDescription';
export class NocoDB implements INodeType {
description: INodeTypeDescription = {
displayName: 'NocoDB',
name: 'nocoDb',
icon: 'file:nocodb.svg',
group: ['input'],
version: 1,
subtitle: '={{$parameter["operation"] + ": " + $parameter["resource"]}}',
description: 'Read, update, write and delete data from NocoDB',
defaults: {
name: 'NocoDB',
},
inputs: ['main'],
outputs: ['main'],
credentials: [
{
name: 'nocoDb',
required: true,
},
],
properties: [
{
displayName: 'Resource',
name: 'resource',
type: 'options',
refactor: Apply more nodelinting rules (#3324) * :pencil2: Alphabetize lint rules * :fire: Remove duplicates * :zap: Update `lintfix` script * :shirt: Apply `node-param-operation-without-no-data-expression` (#3329) * :shirt: Apply `node-param-operation-without-no-data-expression` * :shirt: Add exceptions * :shirt: Apply `node-param-description-weak` (#3328) Co-authored-by: Iván Ovejero <ivov.src@gmail.com> * :shirt: Apply `node-param-option-value-duplicate` (#3331) * :shirt: Apply `node-param-description-miscased-json` (#3337) * :shirt: Apply `node-param-display-name-excess-inner-whitespace` (#3335) Co-authored-by: Iván Ovejero <ivov.src@gmail.com> * :shirt: Apply `node-param-type-options-missing-from-limit` (#3336) * Rule workig as intended * :pencil2: Uncomment rules Co-authored-by: Iván Ovejero <ivov.src@gmail.com> * :shirt: Apply `node-param-option-name-duplicate` (#3338) Co-authored-by: Iván Ovejero <ivov.src@gmail.com> * :shirt: Apply `node-param-description-wrong-for-simplify` (#3334) * :zap: fix * :zap: exceptions * :zap: changed rule ignoring from file to line * :shirt: Apply `node-param-resource-without-no-data-expression` (#3339) * :shirt: Apply `node-param-display-name-untrimmed` (#3341) * :shirt: Apply `node-param-display-name-miscased-id` (#3340) Co-authored-by: Iván Ovejero <ivov.src@gmail.com> * :shirt: Apply `node-param-resource-with-plural-option` (#3342) * :shirt: Apply `node-param-description-wrong-for-upsert` (#3333) * :zap: fix * :zap: replaced record with contact in description * :zap: fix Co-authored-by: Iván Ovejero <ivov.src@gmail.com> * :shirt: Apply `node-param-option-description-identical-to-name` (#3343) * :shirt: Apply `node-param-option-name-containing-star` (#3347) * :shirt: Apply `node-param-display-name-wrong-for-update-fields` (#3348) * :shirt: Apply `node-param-option-name-wrong-for-get-all` (#3345) * :zap: fix * :zap: exceptions * :shirt: Apply node-param-display-name-wrong-for-simplify (#3344) * Rule working as intended * Uncomented other rules * :shirt: Undo and add exceptions Co-authored-by: Iván Ovejero <ivov.src@gmail.com> * :zap: Alphabetize lint rules * :zap: Restore `lintfix` script Co-authored-by: Michael Kret <88898367+michael-radency@users.noreply.github.com> Co-authored-by: agobrech <45268029+agobrech@users.noreply.github.com>
2022-05-20 14:47:24 -07:00
noDataExpression: true,
options: [
{
name: 'Row',
value: 'row',
},
],
default: 'row',
},
{
displayName: 'Operation',
name: 'operation',
type: 'options',
refactor: Apply more nodelinting rules (#3324) * :pencil2: Alphabetize lint rules * :fire: Remove duplicates * :zap: Update `lintfix` script * :shirt: Apply `node-param-operation-without-no-data-expression` (#3329) * :shirt: Apply `node-param-operation-without-no-data-expression` * :shirt: Add exceptions * :shirt: Apply `node-param-description-weak` (#3328) Co-authored-by: Iván Ovejero <ivov.src@gmail.com> * :shirt: Apply `node-param-option-value-duplicate` (#3331) * :shirt: Apply `node-param-description-miscased-json` (#3337) * :shirt: Apply `node-param-display-name-excess-inner-whitespace` (#3335) Co-authored-by: Iván Ovejero <ivov.src@gmail.com> * :shirt: Apply `node-param-type-options-missing-from-limit` (#3336) * Rule workig as intended * :pencil2: Uncomment rules Co-authored-by: Iván Ovejero <ivov.src@gmail.com> * :shirt: Apply `node-param-option-name-duplicate` (#3338) Co-authored-by: Iván Ovejero <ivov.src@gmail.com> * :shirt: Apply `node-param-description-wrong-for-simplify` (#3334) * :zap: fix * :zap: exceptions * :zap: changed rule ignoring from file to line * :shirt: Apply `node-param-resource-without-no-data-expression` (#3339) * :shirt: Apply `node-param-display-name-untrimmed` (#3341) * :shirt: Apply `node-param-display-name-miscased-id` (#3340) Co-authored-by: Iván Ovejero <ivov.src@gmail.com> * :shirt: Apply `node-param-resource-with-plural-option` (#3342) * :shirt: Apply `node-param-description-wrong-for-upsert` (#3333) * :zap: fix * :zap: replaced record with contact in description * :zap: fix Co-authored-by: Iván Ovejero <ivov.src@gmail.com> * :shirt: Apply `node-param-option-description-identical-to-name` (#3343) * :shirt: Apply `node-param-option-name-containing-star` (#3347) * :shirt: Apply `node-param-display-name-wrong-for-update-fields` (#3348) * :shirt: Apply `node-param-option-name-wrong-for-get-all` (#3345) * :zap: fix * :zap: exceptions * :shirt: Apply node-param-display-name-wrong-for-simplify (#3344) * Rule working as intended * Uncomented other rules * :shirt: Undo and add exceptions Co-authored-by: Iván Ovejero <ivov.src@gmail.com> * :zap: Alphabetize lint rules * :zap: Restore `lintfix` script Co-authored-by: Michael Kret <88898367+michael-radency@users.noreply.github.com> Co-authored-by: agobrech <45268029+agobrech@users.noreply.github.com>
2022-05-20 14:47:24 -07:00
noDataExpression: true,
displayOptions: {
show: {
resource: [
'row',
],
},
},
options: [
{
name: 'Create',
value: 'create',
description: 'Create a row',
},
{
name: 'Delete',
value: 'delete',
description: 'Delete a row',
},
{
name: 'Get',
value: 'get',
description: 'Retrieve a row',
},
refactor: Apply more `eslint-plugin-n8n-nodes-base` autofixable rules (#3432) * :zap: Update `lintfix` script * :shirt: Remove unneeded lint exceptions * :shirt: Run baseline `lintfix` * :shirt: Apply `node-param-description-miscased-url` (#3441) * :shirt: Apply `rule node-param-placeholder-miscased-id` (#3443) Co-authored-by: Iván Ovejero <ivov.src@gmail.com> * :shirt: Apply `node-param-option-name-wrong-for-upsert` (#3446) * :shirt: Apply `node-param-min-value-wrong-for-limit` (#3442) Co-authored-by: Iván Ovejero <ivov.src@gmail.com> * Apply `node-param-display-name-wrong-for-dynamic-options` (#3454) * :hammer: fix * :zap: Fix `Assigned To` fields Co-authored-by: Michael Kret <michael.k@radency.com> * :shirt: Apply `rule node-param-default-wrong-for-number` (#3453) * :shirt: Apply `node-param-default-wrong-for-string` (#3452) Co-authored-by: Iván Ovejero <ivov.src@gmail.com> * Apply `node-param-display-name-miscased` (#3449) * :hammer: fix * :hammer: exceptions * :zap: review fixes * :shirt: Apply `node-param-description-lowercase-first-char` (#3451) * :zap: fix * :zap: review fixes * :zap: fix Co-authored-by: Iván Ovejero <ivov.src@gmail.com> * :shirt: Apply `node-param-description-wrong-for-dynamic-options` (#3456) * Rule working as intended * Add rule * :fire: Remove repetitions * :shirt: Add exceptions Co-authored-by: Iván Ovejero <ivov.src@gmail.com> * :shirt: Small fix for `node-param-description-wrong-for-dynamic-options` * :shirt: Apply `node-param-default-wrong-for-fixed-collection` (#3460) * :shirt: Apply `node-param-description-line-break-html-tag` (#3462) * :shirt: Run baseline `lintfix` * :shirt: Apply `node-param-options-type-unsorted-items` (#3459) * :zap: fix * :hammer: exceptions * Add exception for Salesmate and Zoom Co-authored-by: Michael Kret <michael.k@radency.com> Co-authored-by: Iván Ovejero <ivov.src@gmail.com> * :zap: Restore `lintfix` command Co-authored-by: Omar Ajoue <krynble@gmail.com> Co-authored-by: Michael Kret <88898367+michael-radency@users.noreply.github.com> Co-authored-by: agobrech <45268029+agobrech@users.noreply.github.com> Co-authored-by: Michael Kret <michael.k@radency.com> Co-authored-by: brianinoa <54530642+brianinoa@users.noreply.github.com>
2022-06-03 10:23:49 -07:00
{
name: 'Get All',
value: 'getAll',
description: 'Retrieve all rows',
},
{
name: 'Update',
value: 'update',
description: 'Update a row',
},
],
default: 'get',
},
...operationFields,
],
};
async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> {
const items = this.getInputData();
const returnData: IDataObject[] = [];
let responseData;
const resource = this.getNodeParameter('resource', 0) as string;
const operation = this.getNodeParameter('operation', 0) as string;
const projectId = this.getNodeParameter('projectId', 0) as string;
const table = this.getNodeParameter('table', 0) as string;
let returnAll = false;
let endpoint = '';
let requestMethod = '';
let qs: IDataObject = {};
if (resource === 'row') {
if (operation === 'create') {
requestMethod = 'POST';
endpoint = `/nc/${projectId}/api/v1/${table}/bulk`;
const body: IDataObject[] = [];
for (let i = 0; i < items.length; i++) {
const newItem: IDataObject = {};
const dataToSend = this.getNodeParameter('dataToSend', i) as 'defineBelow' | 'autoMapInputData';
if (dataToSend === 'autoMapInputData') {
const incomingKeys = Object.keys(items[i].json);
const rawInputsToIgnore = this.getNodeParameter('inputsToIgnore', i) as string;
const inputDataToIgnore = rawInputsToIgnore.split(',').map(c => c.trim());
for (const key of incomingKeys) {
if (inputDataToIgnore.includes(key)) continue;
newItem[key] = items[i].json[key];
}
} else {
const fields = this.getNodeParameter('fieldsUi.fieldValues', i, []) as Array<{
fieldName: string;
binaryData: boolean;
fieldValue?: string;
binaryProperty?: string;
}>;
for (const field of fields) {
if (!field.binaryData) {
newItem[field.fieldName] = field.fieldValue;
} else if (field.binaryProperty) {
if (!items[i].binary) {
throw new NodeOperationError(this.getNode(), 'No binary data exists on item!');
}
const binaryPropertyName = field.binaryProperty;
if (binaryPropertyName && !items[i].binary![binaryPropertyName]) {
throw new NodeOperationError(this.getNode(), `Binary property ${binaryPropertyName} does not exist on item!`);
}
const binaryData = items[i].binary![binaryPropertyName] as IBinaryData;
const dataBuffer = await this.helpers.getBinaryDataBuffer(i, binaryPropertyName);
const formData = {
file: {
value: dataBuffer,
options: {
filename: binaryData.fileName,
contentType: binaryData.mimeType,
},
},
json: JSON.stringify({
api: 'xcAttachmentUpload',
project_id: projectId,
dbAlias: 'db',
args: {},
}),
};
const qs = { project_id: projectId };
responseData = await apiRequest.call(this, 'POST', '/dashboard', {}, qs, undefined, { formData });
newItem[field.fieldName] = JSON.stringify([responseData]);
}
}
}
body.push(newItem);
}
try {
responseData = await apiRequest.call(this, requestMethod, endpoint, body, qs);
// Calculate ID manually and add to return data
let id = responseData[0];
for (let i = body.length - 1; i >= 0; i--) {
body[i].id = id--;
}
returnData.push(...body);
} catch (error) {
if (this.continueOnFail()) {
returnData.push({ error: error.toString() });
}
throw new NodeApiError(this.getNode(), error);
}
} else if (operation === 'delete') {
requestMethod = 'DELETE';
endpoint = `/nc/${projectId}/api/v1/${table}/bulk`;
const body: IDataObject[] = [];
for (let i = 0; i < items.length; i++) {
const id = this.getNodeParameter('id', i) as string;
body.push({ id });
}
try {
responseData = await apiRequest.call(this, requestMethod, endpoint, body, qs);
returnData.push(...items.map(item => item.json));
} catch (error) {
if (this.continueOnFail()) {
returnData.push({ error: error.toString() });
}
throw new NodeApiError(this.getNode(), error);
}
} else if (operation === 'getAll') {
const data = [];
const downloadAttachments = this.getNodeParameter('downloadAttachments', 0) as boolean;
try {
for (let i = 0; i < items.length; i++) {
requestMethod = 'GET';
endpoint = `/nc/${projectId}/api/v1/${table}`;
returnAll = this.getNodeParameter('returnAll', 0) as boolean;
qs = this.getNodeParameter('options', i, {}) as IDataObject;
if (qs.sort) {
const properties = (qs.sort as IDataObject).property as Array<{ field: string, direction: string }>;
qs.sort = properties.map(prop => `${prop.direction === 'asc' ? '' : '-'}${prop.field}`).join(',');
}
if (qs.fields) {
qs.fields = (qs.fields as IDataObject[]).join(',');
}
if (returnAll === true) {
responseData = await apiRequestAllItems.call(this, requestMethod, endpoint, {}, qs);
} else {
qs.limit = this.getNodeParameter('limit', 0) as number;
responseData = await apiRequest.call(this, requestMethod, endpoint, {}, qs);
}
returnData.push.apply(returnData, responseData);
if (downloadAttachments === true) {
const downloadFieldNames = (this.getNodeParameter('downloadFieldNames', 0) as string).split(',');
const response = await downloadRecordAttachments.call(this, responseData, downloadFieldNames);
data.push(...response);
}
}
if (downloadAttachments) {
return [data];
}
} catch (error) {
if (this.continueOnFail()) {
returnData.push({ error: error.toString() });
}
throw error;
}
} else if (operation === 'get') {
requestMethod = 'GET';
const newItems: INodeExecutionData[] = [];
for (let i = 0; i < items.length; i++) {
try {
const id = this.getNodeParameter('id', i) as string;
endpoint = `/nc/${projectId}/api/v1/${table}/${id}`;
responseData = await apiRequest.call(this, requestMethod, endpoint, {}, qs);
const newItem: INodeExecutionData = { json: responseData };
const downloadAttachments = this.getNodeParameter('downloadAttachments', i) as boolean;
if (downloadAttachments === true) {
const downloadFieldNames = (this.getNodeParameter('downloadFieldNames', i) as string).split(',');
const data = await downloadRecordAttachments.call(this, [responseData], downloadFieldNames);
newItem.binary = data[0].binary;
}
newItems.push(newItem);
} catch (error) {
if (this.continueOnFail()) {
newItems.push({ json: { error: error.toString() } });
continue;
}
throw new NodeApiError(this.getNode(), error);
}
}
return this.prepareOutputData(newItems);
} else if (operation === 'update') {
requestMethod = 'PUT';
endpoint = `/nc/${projectId}/api/v1/${table}/bulk`;
const body: IDataObject[] = [];
for (let i = 0; i < items.length; i++) {
const id = this.getNodeParameter('id', i) as string;
const newItem: IDataObject = { id };
const dataToSend = this.getNodeParameter('dataToSend', i) as 'defineBelow' | 'autoMapInputData';
if (dataToSend === 'autoMapInputData') {
const incomingKeys = Object.keys(items[i].json);
const rawInputsToIgnore = this.getNodeParameter('inputsToIgnore', i) as string;
const inputDataToIgnore = rawInputsToIgnore.split(',').map(c => c.trim());
for (const key of incomingKeys) {
if (inputDataToIgnore.includes(key)) continue;
newItem[key] = items[i].json[key];
}
} else {
const fields = this.getNodeParameter('fieldsUi.fieldValues', i, []) as Array<{
fieldName: string;
upload: boolean;
fieldValue?: string;
binaryProperty?: string;
}>;
for (const field of fields) {
if (!field.upload) {
newItem[field.fieldName] = field.fieldValue;
} else if (field.binaryProperty) {
if (!items[i].binary) {
throw new NodeOperationError(this.getNode(), 'No binary data exists on item!');
}
const binaryPropertyName = field.binaryProperty;
if (binaryPropertyName && !items[i].binary![binaryPropertyName]) {
throw new NodeOperationError(this.getNode(), `Binary property ${binaryPropertyName} does not exist on item!`);
}
const binaryData = items[i].binary![binaryPropertyName] as IBinaryData;
const dataBuffer = await this.helpers.getBinaryDataBuffer(i, binaryPropertyName);
const formData = {
file: {
value: dataBuffer,
options: {
filename: binaryData.fileName,
contentType: binaryData.mimeType,
},
},
json: JSON.stringify({
api: 'xcAttachmentUpload',
project_id: projectId,
dbAlias: 'db',
args: {},
}),
};
const qs = { project_id: projectId };
responseData = await apiRequest.call(this, 'POST', '/dashboard', {}, qs, undefined, { formData });
newItem[field.fieldName] = JSON.stringify([responseData]);
}
}
}
body.push(newItem);
}
try {
responseData = await apiRequest.call(this, requestMethod, endpoint, body, qs);
returnData.push(...body);
} catch (error) {
if (this.continueOnFail()) {
returnData.push({ error: error.toString() });
}
throw new NodeApiError(this.getNode(), error);
}
}
}
return [this.helpers.returnJsonArray(returnData)];
}
}