diff --git a/packages/nodes-base/credentials/BaserowApi.credentials.ts b/packages/nodes-base/credentials/BaserowApi.credentials.ts index 28fd1d89900..9f632114eef 100644 --- a/packages/nodes-base/credentials/BaserowApi.credentials.ts +++ b/packages/nodes-base/credentials/BaserowApi.credentials.ts @@ -1,4 +1,11 @@ -import type { ICredentialType, INodeProperties } from 'n8n-workflow'; +import type { + IAuthenticateGeneric, + ICredentialDataDecryptedObject, + ICredentialTestRequest, + ICredentialType, + IHttpRequestHelper, + INodeProperties, +} from 'n8n-workflow'; // https://api.baserow.io/api/redoc/#section/Authentication @@ -10,17 +17,34 @@ export class BaserowApi implements ICredentialType { documentationUrl = 'baserow'; properties: INodeProperties[] = [ + { + displayName: + "This type of connection (Username & Password) is deprecated. Please create a new credential of type 'Baserow Token API' instead.", + name: 'deprecated', + type: 'notice', + default: '', + }, { displayName: 'Host', name: 'host', type: 'string', default: 'https://api.baserow.io', }, + { + displayName: 'Session Token', + name: 'jwtToken', + type: 'hidden', + typeOptions: { + expirable: true, + }, + default: '', + }, { displayName: 'Username', name: 'username', type: 'string', default: '', + description: 'Email address you use to login to Baserow', }, { displayName: 'Password', @@ -32,4 +56,33 @@ export class BaserowApi implements ICredentialType { }, }, ]; + + async preAuthentication(this: IHttpRequestHelper, credentials: ICredentialDataDecryptedObject) { + const host = (credentials.host as string).replace(/\/$/, ''); + const { token } = (await this.helpers.httpRequest({ + method: 'POST', + url: `${host}/api/user/token-auth/`, + body: { + username: credentials.username, + password: credentials.password, + }, + })) as { token: string }; + return { jwtToken: token }; + } + + authenticate: IAuthenticateGeneric = { + type: 'generic', + properties: { + headers: { + Authorization: '=JWT {{$credentials.jwtToken}}', + }, + }, + }; + + test: ICredentialTestRequest = { + request: { + baseURL: '={{$credentials.host}}', + url: '/api/applications/', + }, + }; } diff --git a/packages/nodes-base/credentials/BaserowTokenApi.credentials.ts b/packages/nodes-base/credentials/BaserowTokenApi.credentials.ts new file mode 100644 index 00000000000..350152552ef --- /dev/null +++ b/packages/nodes-base/credentials/BaserowTokenApi.credentials.ts @@ -0,0 +1,50 @@ +import type { + IAuthenticateGeneric, + ICredentialTestRequest, + ICredentialType, + INodeProperties, +} from 'n8n-workflow'; + +export class BaserowTokenApi implements ICredentialType { + name = 'baserowTokenApi'; + + displayName = 'Baserow Token API'; + + documentationUrl = 'baserow'; + + properties: INodeProperties[] = [ + { + displayName: 'Host', + name: 'host', + type: 'string', + default: 'https://api.baserow.io', + }, + { + displayName: 'Database Token', + name: 'token', + type: 'string', + default: '', + typeOptions: { + password: true, + }, + description: + 'In Baserow, click on top left corner, My settings, Database tokens, Create new.', + }, + ]; + + authenticate: IAuthenticateGeneric = { + type: 'generic', + properties: { + headers: { + Authorization: '=Token {{$credentials.token}}', + }, + }, + }; + + test: ICredentialTestRequest = { + request: { + baseURL: '={{$credentials.host}}', + url: '/api/database/tables/all-tables/', + }, + }; +} diff --git a/packages/nodes-base/nodes/Baserow/Baserow.node.ts b/packages/nodes-base/nodes/Baserow/Baserow.node.ts index 19398d43510..937cd23c22b 100644 --- a/packages/nodes-base/nodes/Baserow/Baserow.node.ts +++ b/packages/nodes-base/nodes/Baserow/Baserow.node.ts @@ -11,13 +11,11 @@ import { import { baserowApiRequest, baserowApiRequestAllItems, - getJwtToken, TableFieldMapper, toOptions, } from './GenericFunctions'; import { operationFields } from './OperationDescription'; import type { - BaserowCredentials, FieldsUiValues, GetAllAdditionalOptions, LoadedResource, @@ -25,13 +23,17 @@ import type { Row, } from './types'; +function getCredentialType(authentication: string): string { + return authentication === 'databaseToken' ? 'baserowTokenApi' : 'baserowApi'; +} + export class Baserow implements INodeType { description: INodeTypeDescription = { displayName: 'Baserow', name: 'baserow', icon: 'file:baserow.svg', group: ['output'], - version: 1, + version: [1, 1.1], description: 'Consume the Baserow API', subtitle: '={{$parameter["operation"] + ":" + $parameter["resource"]}}', defaults: { @@ -44,9 +46,39 @@ export class Baserow implements INodeType { { name: 'baserowApi', required: true, + displayOptions: { + show: { + authentication: ['usernamePassword'], + }, + }, + }, + { + name: 'baserowTokenApi', + required: true, + displayOptions: { + show: { + authentication: ['databaseToken'], + }, + }, }, ], properties: [ + { + displayName: 'Authentication', + name: 'authentication', + type: 'options', + options: [ + { + name: 'Username & Password', + value: 'usernamePassword', + }, + { + name: 'Database Token', + value: 'databaseToken', + }, + ], + default: 'usernamePassword', + }, { displayName: 'Resource', name: 'resource', @@ -71,6 +103,24 @@ export class Baserow implements INodeType { }, }, options: [ + { + name: 'Batch Create', + value: 'batchCreate', + description: 'Create up to 200 rows in one request', + action: 'Create multiple rows', + }, + { + name: 'Batch Delete', + value: 'batchDelete', + description: 'Delete up to 200 rows in one request', + action: 'Delete multiple rows', + }, + { + name: 'Batch Update', + value: 'batchUpdate', + description: 'Update up to 200 rows in one request', + action: 'Update multiple rows', + }, { name: 'Create', value: 'create', @@ -111,44 +161,50 @@ export class Baserow implements INodeType { methods = { loadOptions: { async getDatabaseIds(this: ILoadOptionsFunctions) { - const credentials = await this.getCredentials('baserowApi'); - const jwtToken = await getJwtToken.call(this, credentials); + const credentialType = getCredentialType( + this.getNodeParameter('authentication', 0) as string, + ); const endpoint = '/api/applications/'; const databases = (await baserowApiRequest.call( this, 'GET', endpoint, - jwtToken, + credentialType, )) as LoadedResource[]; - // Baserow has different types of applications, we only want the databases - // https://api.baserow.io/api/redoc/#tag/Applications/operation/list_all_applications return toOptions(databases.filter((database) => database.type === 'database')); }, async getTableIds(this: ILoadOptionsFunctions) { - const credentials = await this.getCredentials('baserowApi'); - const jwtToken = await getJwtToken.call(this, credentials); - const databaseId = this.getNodeParameter('databaseId', 0) as string; - const endpoint = `/api/database/tables/database/${databaseId}/`; + const authentication = this.getNodeParameter('authentication', 0) as string; + const credentialType = getCredentialType(authentication); + + let endpoint: string; + if (authentication === 'databaseToken') { + endpoint = '/api/database/tables/all-tables/'; + } else { + const databaseId = this.getNodeParameter('databaseId', 0) as string; + endpoint = `/api/database/tables/database/${databaseId}/`; + } const tables = (await baserowApiRequest.call( this, 'GET', endpoint, - jwtToken, + credentialType, )) as LoadedResource[]; return toOptions(tables); }, async getTableFields(this: ILoadOptionsFunctions) { - const credentials = await this.getCredentials('baserowApi'); - const jwtToken = await getJwtToken.call(this, credentials); + const credentialType = getCredentialType( + this.getNodeParameter('authentication', 0) as string, + ); const tableId = this.getNodeParameter('tableId', 0) as string; const endpoint = `/api/database/fields/table/${tableId}/`; const fields = (await baserowApiRequest.call( this, 'GET', endpoint, - jwtToken, + credentialType, )) as LoadedResource[]; return toOptions(fields); }, @@ -162,11 +218,151 @@ export class Baserow implements INodeType { const operation = this.getNodeParameter('operation', 0) as Operation; const tableId = this.getNodeParameter('tableId', 0) as string; - const credentials = await this.getCredentials('baserowApi'); - const jwtToken = await getJwtToken.call(this, credentials); - const fields = await mapper.getTableFields.call(this, tableId, jwtToken); + const credentialType = getCredentialType(this.getNodeParameter('authentication', 0) as string); + const fields = await mapper.getTableFields.call(this, tableId, credentialType); mapper.createMappings(fields); + if (operation === 'batchCreate') { + // ---------------------------------- + // batchCreate + // ---------------------------------- + + // https://api.baserow.io/api/redoc/#tag/Database-table-rows/operation/batch_create_database_table_rows + + const dataToSend = this.getNodeParameter('dataToSend', 0) as + | 'defineBelow' + | 'autoMapInputData'; + const itemsPayload: IDataObject[] = []; + + if (dataToSend === 'autoMapInputData') { + for (let i = 0; i < items.length; i++) { + const body: IDataObject = {}; + 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; + body[key] = items[i].json[key]; + mapper.namesToIds(body); + } + itemsPayload.push(body); + } + } else { + const rowsUi = this.getNodeParameter('rowsUi.rowValues', 0, []) as Array<{ + fieldsUi: { fieldValues: Array<{ fieldId: string; fieldValue: string }> }; + }>; + for (const row of rowsUi) { + const body: IDataObject = {}; + for (const field of row.fieldsUi.fieldValues) { + body[`field_${field.fieldId}`] = field.fieldValue; + } + itemsPayload.push(body); + } + } + + const endpoint = `/api/database/rows/table/${tableId}/batch/`; + const response = await baserowApiRequest.call(this, 'POST', endpoint, credentialType, { + items: itemsPayload, + }); + + response.items.forEach((row: Row) => mapper.idsToNames(row)); + const executionData = this.helpers.constructExecutionMetaData( + this.helpers.returnJsonArray(response.items), + { itemData: { item: 0 } }, + ); + returnData.push.apply(returnData, executionData); + return [returnData]; + } + + if (operation === 'batchUpdate') { + // ---------------------------------- + // batchUpdate + // ---------------------------------- + + // https://api.baserow.io/api/redoc/#tag/Database-table-rows/operation/batch_update_database_table_rows + + const dataToSend = this.getNodeParameter('dataToSend', 0) as + | 'defineBelow' + | 'autoMapInputData'; + const itemsPayload: IDataObject[] = []; + + if (dataToSend === 'autoMapInputData') { + for (let i = 0; i < items.length; i++) { + const body: IDataObject = {}; + body.id = items[i].json.id; + + 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; + body[key] = items[i].json[key]; + mapper.namesToIds(body); + } + itemsPayload.push(body); + } + } else { + const rowsUi = this.getNodeParameter('rowsUi.rowValues', 0, []) as Array<{ + id: string; + fieldsUi: { fieldValues: Array<{ fieldId: string; fieldValue: string }> }; + }>; + for (const row of rowsUi) { + const body: IDataObject = { id: row.id }; + for (const field of row.fieldsUi.fieldValues) { + body[`field_${field.fieldId}`] = field.fieldValue; + } + itemsPayload.push(body); + } + } + + const endpoint = `/api/database/rows/table/${tableId}/batch/`; + const response = await baserowApiRequest.call(this, 'PATCH', endpoint, credentialType, { + items: itemsPayload, + }); + + response.items.forEach((row: Row) => mapper.idsToNames(row)); + const executionData = this.helpers.constructExecutionMetaData( + this.helpers.returnJsonArray(response.items), + { itemData: { item: 0 } }, + ); + returnData.push.apply(returnData, executionData); + return [returnData]; + } + + if (operation === 'batchDelete') { + // ---------------------------------- + // batchDelete + // ---------------------------------- + + // https://api.baserow.io/api/redoc/#tag/Database-table-rows/operation/batch_delete_database_table_rows + + const dataToSend = this.getNodeParameter('dataToSend', 0) as + | 'defineBelow' + | 'autoMapInputData'; + let ids: string[]; + + if (dataToSend === 'autoMapInputData') { + const propertyName = this.getNodeParameter('rowIdProperty', 0) as string; + ids = items.map((item) => { + return String(item.json[propertyName]); + }); + } else { + ids = this.getNodeParameter('rowIds', 0) as string[]; + } + + const endpoint = `/api/database/rows/table/${tableId}/batch-delete/`; + await baserowApiRequest.call(this, 'POST', endpoint, credentialType, { items: ids }); + + const executionData = this.helpers.constructExecutionMetaData( + this.helpers.returnJsonArray([{ success: true, deleted: ids }]), + { itemData: { item: 0 } }, + ); + returnData.push(...executionData); + return [returnData]; + } + for (let i = 0; i < items.length; i++) { try { if (operation === 'getAll') { @@ -208,7 +404,7 @@ export class Baserow implements INodeType { this, 'GET', endpoint, - jwtToken, + credentialType, {}, qs, )) as Row[]; @@ -218,7 +414,7 @@ export class Baserow implements INodeType { this.helpers.returnJsonArray(rows), { itemData: { item: i } }, ); - returnData.push(...executionData); + returnData.push.apply(returnData, executionData); } else if (operation === 'get') { // ---------------------------------- // get @@ -228,14 +424,14 @@ export class Baserow implements INodeType { const rowId = this.getNodeParameter('rowId', i) as string; const endpoint = `/api/database/rows/table/${tableId}/${rowId}/`; - const row = await baserowApiRequest.call(this, 'GET', endpoint, jwtToken); + const row = await baserowApiRequest.call(this, 'GET', endpoint, credentialType); mapper.idsToNames(row as Row); const executionData = this.helpers.constructExecutionMetaData( this.helpers.returnJsonArray(row as Row), { itemData: { item: i } }, ); - returnData.push(...executionData); + returnData.push.apply(returnData, executionData); } else if (operation === 'create') { // ---------------------------------- // create @@ -267,14 +463,20 @@ export class Baserow implements INodeType { } const endpoint = `/api/database/rows/table/${tableId}/`; - const createdRow = await baserowApiRequest.call(this, 'POST', endpoint, jwtToken, body); + const createdRow = await baserowApiRequest.call( + this, + 'POST', + endpoint, + credentialType, + body, + ); mapper.idsToNames(createdRow as Row); const executionData = this.helpers.constructExecutionMetaData( this.helpers.returnJsonArray(createdRow as Row), { itemData: { item: i } }, ); - returnData.push(...executionData); + returnData.push.apply(returnData, executionData); } else if (operation === 'update') { // ---------------------------------- // update @@ -308,14 +510,20 @@ export class Baserow implements INodeType { } const endpoint = `/api/database/rows/table/${tableId}/${rowId}/`; - const updatedRow = await baserowApiRequest.call(this, 'PATCH', endpoint, jwtToken, body); + const updatedRow = await baserowApiRequest.call( + this, + 'PATCH', + endpoint, + credentialType, + body, + ); mapper.idsToNames(updatedRow as Row); const executionData = this.helpers.constructExecutionMetaData( this.helpers.returnJsonArray(updatedRow as Row), { itemData: { item: i } }, ); - returnData.push(...executionData); + returnData.push.apply(returnData, executionData); } else if (operation === 'delete') { // ---------------------------------- // delete @@ -326,13 +534,13 @@ export class Baserow implements INodeType { const rowId = this.getNodeParameter('rowId', i) as string; const endpoint = `/api/database/rows/table/${tableId}/${rowId}/`; - await baserowApiRequest.call(this, 'DELETE', endpoint, jwtToken); + await baserowApiRequest.call(this, 'DELETE', endpoint, credentialType); const executionData = this.helpers.constructExecutionMetaData( [{ json: { success: true } }], { itemData: { item: i } }, ); - returnData.push(...executionData); + returnData.push.apply(returnData, executionData); } } catch (error) { if (this.continueOnFail()) { diff --git a/packages/nodes-base/nodes/Baserow/GenericFunctions.ts b/packages/nodes-base/nodes/Baserow/GenericFunctions.ts index ba33755e2fc..71856175da8 100644 --- a/packages/nodes-base/nodes/Baserow/GenericFunctions.ts +++ b/packages/nodes-base/nodes/Baserow/GenericFunctions.ts @@ -8,7 +8,7 @@ import type { } from 'n8n-workflow'; import { NodeApiError } from 'n8n-workflow'; -import type { Accumulator, BaserowCredentials, LoadedResource } from './types'; +import type { BaserowCredentials, LoadedResource } from './types'; /** * Make a request to Baserow API. @@ -17,20 +17,18 @@ export async function baserowApiRequest( this: IExecuteFunctions | ILoadOptionsFunctions, method: IHttpRequestMethods, endpoint: string, - jwtToken: string, + credentialType: string, body: IDataObject = {}, qs: IDataObject = {}, ) { - const credentials = await this.getCredentials('baserowApi'); + const credentials = await this.getCredentials(credentialType); + const host = (credentials.host as string).replace(/\/$/, ''); const options: IRequestOptions = { - headers: { - Authorization: `JWT ${jwtToken}`, - }, method, body, qs, - uri: `${credentials.host}${endpoint}`, + uri: `${host}${endpoint}`, json: true, }; @@ -43,7 +41,7 @@ export async function baserowApiRequest( } try { - return await this.helpers.request(options); + return await this.helpers.requestWithAuthentication.call(this, credentialType, options); } catch (error) { throw new NodeApiError(this.getNode(), error as JsonObject); } @@ -56,7 +54,7 @@ export async function baserowApiRequestAllItems( this: IExecuteFunctions, method: IHttpRequestMethods, endpoint: string, - jwtToken: string, + credentialType: string, body: IDataObject, qs: IDataObject = {}, ): Promise { @@ -70,8 +68,8 @@ export async function baserowApiRequestAllItems( const limit = this.getNodeParameter('limit', 0, 0); do { - responseData = await baserowApiRequest.call(this, method, endpoint, jwtToken, body, qs); - returnData.push(...(responseData.results as IDataObject[])); + responseData = await baserowApiRequest.call(this, method, endpoint, credentialType, body, qs); + returnData.push.apply(returnData, responseData.results as IDataObject[]); if (!returnAll && returnData.length > limit) { return returnData.slice(0, limit); @@ -83,42 +81,17 @@ export async function baserowApiRequestAllItems( return returnData; } -/** - * Get a JWT token based on Baserow account username and password. - */ -export async function getJwtToken( - this: IExecuteFunctions | ILoadOptionsFunctions, - { username, password, host }: BaserowCredentials, -) { - const options: IRequestOptions = { - method: 'POST', - body: { - username, - password, - }, - uri: `${host}/api/user/token-auth/`, - json: true, - }; - - try { - const { token } = (await this.helpers.request(options)) as { token: string }; - return token; - } catch (error) { - throw new NodeApiError(this.getNode(), error as JsonObject); - } -} - export async function getFieldNamesAndIds( this: IExecuteFunctions, tableId: string, - jwtToken: string, + credentialType: string, ) { const endpoint = `/api/database/fields/table/${tableId}/`; const response = (await baserowApiRequest.call( this, 'GET', endpoint, - jwtToken, + credentialType, )) as LoadedResource[]; return { @@ -143,10 +116,10 @@ export class TableFieldMapper { async getTableFields( this: IExecuteFunctions, table: string, - jwtToken: string, + credentialType: string, ): Promise { const endpoint = `/api/database/fields/table/${table}/`; - return await baserowApiRequest.call(this, 'GET', endpoint, jwtToken); + return await baserowApiRequest.call(this, 'GET', endpoint, credentialType); } createMappings(tableFields: LoadedResource[]) { @@ -155,14 +128,14 @@ export class TableFieldMapper { } private createIdToNameMapping(responseData: LoadedResource[]) { - return responseData.reduce((acc, cur) => { + return responseData.reduce>((acc, cur) => { acc[`field_${cur.id}`] = cur.name; return acc; }, {}); } private createNameToIdMapping(responseData: LoadedResource[]) { - return responseData.reduce((acc, cur) => { + return responseData.reduce>((acc, cur) => { acc[cur.name] = `field_${cur.id}`; return acc; }, {}); diff --git a/packages/nodes-base/nodes/Baserow/OperationDescription.ts b/packages/nodes-base/nodes/Baserow/OperationDescription.ts index 36332d1423a..02966d0a5c0 100644 --- a/packages/nodes-base/nodes/Baserow/OperationDescription.ts +++ b/packages/nodes-base/nodes/Baserow/OperationDescription.ts @@ -8,13 +8,18 @@ export const operationFields: INodeProperties[] = [ displayName: 'Database Name or ID', name: 'databaseId', type: 'options', - default: '', + default: '0', required: true, description: 'Database to operate on. Choose from the list, or specify an ID using an expression.', typeOptions: { loadOptionsMethod: 'getDatabaseIds', }, + displayOptions: { + hide: { + authentication: ['databaseToken'], + }, + }, }, { displayName: 'Table Name or ID', @@ -85,7 +90,7 @@ export const operationFields: INodeProperties[] = [ ], displayOptions: { show: { - operation: ['create', 'update'], + operation: ['create', 'update', 'batchCreate', 'batchUpdate'], }, }, default: 'defineBelow', @@ -97,7 +102,7 @@ export const operationFields: INodeProperties[] = [ type: 'string', displayOptions: { show: { - operation: ['create', 'update'], + operation: ['create', 'update', 'batchCreate', 'batchUpdate'], dataToSend: ['autoMapInputData'], }, }, @@ -149,10 +154,107 @@ export const operationFields: INodeProperties[] = [ }, ], }, + { + displayName: 'Rows', + name: 'rowsUi', + type: 'fixedCollection', + typeOptions: { + multipleValues: true, + }, + placeholder: 'Add Row', + displayOptions: { + show: { + operation: ['batchCreate', 'batchUpdate'], + dataToSend: ['defineBelow'], + }, + }, + default: [], + options: [ + { + name: 'rowValues', + displayName: 'Row', + values: [ + { + displayName: 'Row ID', + name: 'id', + type: 'string', + displayOptions: { + show: { + '/operation': ['batchUpdate'], + }, + }, + default: '', + required: true, + description: 'Row ID to update (required for batch update)', + }, + { + displayName: 'Fields', + name: 'fieldsUi', + type: 'fixedCollection', + typeOptions: { + multipleValues: true, + multipleValueButtonText: 'Add Field', + }, + default: {}, + options: [ + { + name: 'fieldValues', + displayName: 'Field', + values: [ + { + displayName: 'Field Name or ID', + name: 'fieldId', + type: 'options', + description: + 'Choose from the list, or specify an ID using an expression', + typeOptions: { + loadOptionsDependsOn: ['tableId'], + loadOptionsMethod: 'getTableFields', + }, + default: '', + }, + { + displayName: 'Field Value', + name: 'fieldValue', + type: 'string', + default: '', + }, + ], + }, + ], + }, + ], + }, + ], + }, // ---------------------------------- // delete // ---------------------------------- + { + displayName: 'Data to Send', + name: 'dataToSend', + type: 'options', + options: [ + { + name: 'Auto-Map Input Data', + value: 'autoMapInputData', + description: 'Collect row IDs from input items automatically', + }, + { + name: 'Define Below', + value: 'defineBelow', + description: 'Manually specify row IDs', + }, + ], + displayOptions: { + show: { + operation: ['batchDelete'], + }, + }, + default: 'defineBelow', + description: 'Choose whether to manually enter row IDs or map them from input data', + }, { displayName: 'Row ID', name: 'rowId', @@ -166,6 +268,36 @@ export const operationFields: INodeProperties[] = [ required: true, description: 'ID of the row to delete', }, + { + displayName: 'Row IDs', + name: 'rowIds', + type: 'string', + typeOptions: { + multipleValues: true, + }, + default: [], + placeholder: 'Add Row ID', + displayOptions: { + show: { + operation: ['batchDelete'], + dataToSend: ['defineBelow'], + }, + }, + description: 'IDs of the rows to delete', + }, + { + displayName: 'Property Containing Row ID', + name: 'rowIdProperty', + type: 'string', + default: 'id', + displayOptions: { + show: { + operation: ['batchDelete'], + dataToSend: ['autoMapInputData'], + }, + }, + description: 'Name of the property in each input item that contains the row ID', + }, // ---------------------------------- // getAll @@ -243,112 +375,326 @@ export const operationFields: INodeProperties[] = [ name: 'operator', description: 'Operator to compare field and value with', type: 'options', + /* eslint-disable n8n-nodes-base/node-param-options-type-unsorted-items */ options: [ - { - name: 'Contains', - value: 'contains', - description: 'Field contains value', - }, - { - name: 'Contains Not', - value: 'contains_not', - description: 'Field does not contain value', - }, - { - name: 'Date After Date', - value: 'date_after', - description: "Field after this date. Format: 'YYYY-MM-DD'.", - }, - { - name: 'Date Before Date', - value: 'date_before', - description: "Field before this date. Format: 'YYYY-MM-DD'.", - }, - { - name: 'Date Equal', - value: 'date_equal', - description: "Field is date. Format: 'YYYY-MM-DD'.", - }, - { - name: 'Date Equals Month', - value: 'date_equals_month', - description: 'Field in this month. Format: string.', - }, - { - name: 'Date Equals Today', - value: 'date_equals_today', - description: 'Field is today. Format: string.', - }, - { - name: 'Date Equals Year', - value: 'date_equals_year', - description: 'Field in this year. Format: string.', - }, - { - name: 'Date Not Equal', - value: 'date_not_equal', - description: "Field is not date. Format: 'YYYY-MM-DD'.", - }, { name: 'Equal', value: 'equal', - description: 'Field is equal to value', - }, - { - name: 'Filename Contains', - value: 'filename_contains', - description: 'Field filename contains value', - }, - { - name: 'Higher Than', - value: 'higher_than', - description: 'Field is higher than value', - }, - { - name: 'Is Empty', - value: 'empty', - description: 'Field is empty', - }, - { - name: 'Is Not Empty', - value: 'not_empty', - description: 'Field is not empty', - }, - { - name: 'Is True', - value: 'boolean', - description: 'Boolean field is true', - }, - { - name: 'Link Row Does Not Have', - value: 'link_row_has_not', - description: 'Field does not have link ID', - }, - { - name: 'Link Row Has', - value: 'link_row_has', - description: 'Field has link ID', - }, - { - name: 'Lower Than', - value: 'lower_than', - description: 'Field is lower than value', + description: 'Field value is exactly equal to the given value', }, { name: 'Not Equal', value: 'not_equal', - description: 'Field is not equal to value', + description: 'Field value is not equal to the given value', + }, + { + name: 'Contains', + value: 'contains', + description: 'Field value contains the given substring (case-insensitive)', + }, + { + name: 'Contains Not', + value: 'contains_not', + description: + 'Field value does not contain the given substring (case-insensitive)', + }, + { + name: 'Contains Word', + value: 'contains_word', + description: + 'Field contains the full word (case-insensitive match on word boundaries)', + }, + { + name: 'Does Not Contain Word', + value: 'doesnt_contain_word', + description: 'Field does not contain the full word (case-insensitive)', + }, + { + name: 'Length Is Lower Than', + value: 'length_is_lower_than', + description: 'Field value length is shorter than the given number', + }, + { + name: 'Higher Than', + value: 'higher_than', + description: 'Field value is greater than the given number', + }, + { + name: 'Higher Than or Equal', + value: 'higher_than_or_equal', + description: 'Field value is greater than or equal to the given number', + }, + { + name: 'Lower Than', + value: 'lower_than', + description: 'Field value is less than the given number', + }, + { + name: 'Lower Than or Equal', + value: 'lower_than_or_equal', + description: 'Field value is less than or equal to the given number', + }, + { + name: 'Is Even And Whole', + value: 'is_even_and_whole', + description: 'Field value is an even whole number (no decimals)', + }, + { + name: 'Date Is', + value: 'date_is', + description: + 'Date matches the given day. Format: `Europe/Berlin??2024-09-17` (Timezone??YYYY-MM-DD).', + }, + { + name: 'Date Is Not', + value: 'date_is_not', + description: 'Date does not match the given day. Format: `UTC??2024-09-17`.', + }, + { + name: 'Date Is Before', + value: 'date_is_before', + description: + 'Date is strictly before the given day. Format: `UTC??2024-09-17`.', + }, + { + name: 'Date Is On Or Before', + value: 'date_is_on_or_before', + description: + 'Date is before or equal to the given day. Format: `UTC??2024-09-17`.', + }, + { + name: 'Date Is After', + value: 'date_is_after', + description: 'Date is strictly after the given day. Format: `UTC??2024-09-17`.', + }, + { + name: 'Date Is On Or After', + value: 'date_is_on_or_after', + description: + 'Date is after or equal to the given day. Format: `UTC??2024-09-17`.', + }, + { + name: 'Date Is Within', + value: 'date_is_within', + description: + 'Date is within the next X days. Format: `UTC??30` (Timezone??NumberOfDays).', + }, + { + name: 'Date Equals Today', + value: 'date_equals_today', + description: + 'Date is today. Format: `UTC??today`. (Deprecated but kept for compatibility).', + }, + { + name: 'Date Equals Month', + value: 'date_equals_month', + description: + 'Date is in the given month. Format: `UTC??2024-09`. (Deprecated but kept for compatibility).', + }, + { + name: 'Date Equals Year', + value: 'date_equals_year', + description: + 'Date is in the given year. Format: `UTC??2024`. (Deprecated but kept for compatibility).', + }, + { + name: 'Date Equals Day Of Month', + value: 'date_equals_day_of_month', + description: 'Day of month matches the given number. Format: `UTC??15` (1-31).', + }, + { + name: 'Date Equal (Deprecated)', + value: 'date_equal', + description: + 'Field is date. Format: `UTC?YYYY-MM-DD`. Prefer using Date Is (date_is).', + }, + { + name: 'Date Not Equal (Deprecated)', + value: 'date_not_equal', + description: + 'Field is not date. Format: `UTC?YYYY-MM-DD`. Prefer using Date Is Not (date_is_not).', + }, + { + name: 'Date Before (Deprecated)', + value: 'date_before', + description: + 'Field before this date. Format: `UTC?YYYY-MM-DD`. Prefer using Date Is Before (date_is_before).', + }, + { + name: 'Date Before Or Equal (Deprecated)', + value: 'date_before_or_equal', + description: + 'Field on or before this date. Format: `UTC?YYYY-MM-DD`. Prefer using Date Is On Or Before (date_is_on_or_before).', + }, + { + name: 'Date After (Deprecated)', + value: 'date_after', + description: + 'Field after this date. Format: `UTC?YYYY-MM-DD`. Prefer using Date Is After (date_is_after).', + }, + { + name: 'Date After Or Equal (Deprecated)', + value: 'date_after_or_equal', + description: + 'Field after or equal to this date. Format: `UTC?YYYY-MM-DD`. Prefer using Date Is On Or After (date_is_on_or_after).', + }, + { + name: 'Date After Days Ago (Deprecated)', + value: 'date_after_days_ago', + description: + 'Date is after X days ago. Format: `UTC?10`. Prefer using Date Is On Or After with NR_DAYS_AGO.', + }, + { + name: 'Date Within Days (Deprecated)', + value: 'date_within_days', + description: + 'Date is within N days from today. Format: `UTC?30`. Prefer using Date Is Within (date_is_within).', + }, + { + name: 'Date Within Weeks (Deprecated)', + value: 'date_within_weeks', + description: + 'Date is within N weeks from today. Format: `UTC?4`. Prefer using Date Is Within.', + }, + { + name: 'Date Within Months (Deprecated)', + value: 'date_within_months', + description: + 'Date is within N months from today. Format: `UTC?3`. Prefer using Date Is Within.', + }, + { + name: 'Date Equals Days Ago (Deprecated)', + value: 'date_equals_days_ago', + description: 'Date is exactly N days ago. Format: `UTC?5`.', + }, + { + name: 'Date Equals Months Ago (Deprecated)', + value: 'date_equals_months_ago', + description: 'Date is exactly N months ago. Format: `UTC?2`.', + }, + { + name: 'Date Equals Years Ago (Deprecated)', + value: 'date_equals_years_ago', + description: 'Date is exactly N years ago. Format: `UTC?1`.', + }, + { + name: 'Date Before Today (Deprecated)', + value: 'date_before_today', + description: + 'Date is before today. Format: `UTC`. Prefer using Date Is Before with operator TODAY.', + }, + { + name: 'Date After Today (Deprecated)', + value: 'date_after_today', + description: + 'Date is after today. Format: `UTC`. Prefer using Date Is After with operator TODAY.', + }, + { + name: 'Date Equals Current Week (Deprecated)', + value: 'date_equals_week', + description: + 'Date is within current week. Format: `UTC`. Prefer using Date Is with THIS_WEEK.', + }, + { + name: 'Filename Contains', + value: 'filename_contains', + description: 'Filename contains the given substring', + }, + { + name: 'Has File Type', + value: 'has_file_type', + description: 'File type is "image" or "document"', + }, + { + name: 'Files Lower Than', + value: 'files_lower_than', + description: 'Number of attached files is less than the given number', }, { name: 'Single Select Equal', value: 'single_select_equal', - description: 'Field selected option is value', + description: 'Single select option matches given option ID', }, { name: 'Single Select Not Equal', value: 'single_select_not_equal', - description: 'Field selected option is not value', + description: 'Single select option does not match given option ID', }, + { + name: 'Single Select Is Any Of', + value: 'single_select_is_any_of', + description: + 'Single select option is one of the given option IDs. Format: `1,2,3`.', + }, + { + name: 'Single Select Is None Of', + value: 'single_select_is_none_of', + description: + 'Single select option is none of the given option IDs. Format: `1,2,3`.', + }, + { + name: 'Multiple Select Has', + value: 'multiple_select_has', + description: + 'Multiple select has at least one of the given option IDs. Format: `1,2,3`.', + }, + { + name: 'Multiple Select Has Not', + value: 'multiple_select_has_not', + description: + 'Multiple select has none of the given option IDs. Format: `1,2,3`.', + }, + { + name: 'Collaborators Has', + value: 'multiple_collaborators_has', + description: 'Field includes the given user ID', + }, + { + name: 'Collaborators Has Not', + value: 'multiple_collaborators_has_not', + description: 'Field excludes the given user ID', + }, + { + name: 'User Is', + value: 'user_is', + description: 'Row created by or last modified by the given user ID', + }, + { + name: 'User Is Not', + value: 'user_is_not', + description: 'Row was not created or modified by the given user ID', + }, + { + name: 'Link Row Has', + value: 'link_row_has', + description: 'Field links to the given row ID', + }, + { + name: 'Link Row Has Not', + value: 'link_row_has_not', + description: 'Field does not link to the given row ID', + }, + { + name: 'Link Row Contains', + value: 'link_row_contains', + description: 'Linked row value contains the given text (case-insensitive)', + }, + { + name: 'Link Row Not Contains', + value: 'link_row_not_contains', + description: 'Linked row value does not contain the given text', + }, + { + name: 'Is True', + value: 'boolean', + description: 'Boolean field is true (false if not set)', + }, + { + name: 'Is Empty', + value: 'empty', + description: 'Field is empty (null or blank)', + }, + { name: 'Is Not Empty', value: 'not_empty', description: 'Field is not empty' }, ], default: 'equal', }, diff --git a/packages/nodes-base/nodes/Baserow/__tests__/GenericFunctions.test.ts b/packages/nodes-base/nodes/Baserow/__tests__/GenericFunctions.test.ts index 6a6170407f1..6d238413f74 100644 --- a/packages/nodes-base/nodes/Baserow/__tests__/GenericFunctions.test.ts +++ b/packages/nodes-base/nodes/Baserow/__tests__/GenericFunctions.test.ts @@ -4,7 +4,6 @@ import { NodeApiError } from 'n8n-workflow'; import { baserowApiRequest, baserowApiRequestAllItems, - getJwtToken, getFieldNamesAndIds, toOptions, TableFieldMapper, @@ -13,11 +12,9 @@ import { describe('Baserow > GenericFunctions', () => { const mockExecuteFunctions: any = { helpers: { - request: jest.fn(), + requestWithAuthentication: jest.fn(), }, getCredentials: jest.fn().mockResolvedValue({ - username: 'nathan@n8n.io', - password: 'this-is-a-fake-password', host: 'https://api.baserow.io', }), getNodeParameter: jest.fn(), @@ -26,25 +23,38 @@ describe('Baserow > GenericFunctions', () => { beforeEach(() => { jest.clearAllMocks(); + mockExecuteFunctions.getCredentials.mockResolvedValue({ + host: 'https://api.baserow.io', + }); }); describe('baserowApiRequest', () => { it('should return data on success', async () => { - mockExecuteFunctions.helpers.request.mockResolvedValue({ success: true }); + mockExecuteFunctions.helpers.requestWithAuthentication.mockResolvedValue({ + success: true, + }); const result = await baserowApiRequest.call( mockExecuteFunctions, 'GET', '/endpoint', - 'testJwt', + 'baserowApi', ); expect(result).toEqual({ success: true }); - expect(mockExecuteFunctions.helpers.request).toHaveBeenCalled(); + expect(mockExecuteFunctions.helpers.requestWithAuthentication).toHaveBeenCalledWith( + 'baserowApi', + expect.objectContaining({ + method: 'GET', + uri: 'https://api.baserow.io/endpoint', + }), + ); }); it('should throw NodeApiError on failure', async () => { - mockExecuteFunctions.helpers.request.mockRejectedValue({ error: 'fail' }); + mockExecuteFunctions.helpers.requestWithAuthentication.mockRejectedValue({ + error: 'fail', + }); await expect( - baserowApiRequest.call(mockExecuteFunctions, 'GET', '/endpoint', 'testJwt'), + baserowApiRequest.call(mockExecuteFunctions, 'GET', '/endpoint', 'baserowApi'), ).rejects.toThrow(NodeApiError); }); }); @@ -54,7 +64,7 @@ describe('Baserow > GenericFunctions', () => { mockExecuteFunctions.getNodeParameter .mockReturnValueOnce(true) // returnAll .mockReturnValue(1000); // limit - mockExecuteFunctions.helpers.request + mockExecuteFunctions.helpers.requestWithAuthentication .mockResolvedValueOnce({ results: [{ data: 1 }], next: 'page2' }) .mockResolvedValueOnce({ results: [{ data: 2 }], next: null }); @@ -62,7 +72,7 @@ describe('Baserow > GenericFunctions', () => { mockExecuteFunctions, 'GET', '/endpoint', - 'testJwt', + 'baserowApi', {}, {}, ); @@ -71,36 +81,13 @@ describe('Baserow > GenericFunctions', () => { }); }); - describe('getJwtToken', () => { - it('should return a token', async () => { - mockExecuteFunctions.helpers.request.mockResolvedValue({ token: 'mockToken' }); - const result = await getJwtToken.call(mockExecuteFunctions, { - username: 'nathan@n8n.io', - password: 'this-is-a-fake-password', - host: 'https://api.baserow.io', - }); - expect(result).toBe('mockToken'); - }); - - it('should throw NodeApiError if request fails', async () => { - mockExecuteFunctions.helpers.request.mockRejectedValue({ error: 'fail' }); - await expect( - getJwtToken.call(mockExecuteFunctions, { - username: 'nathan@n8n.io', - password: 'this-is-a-fake-password', - host: 'https://api.baserow.io', - }), - ).rejects.toThrow(NodeApiError); - }); - }); - describe('getFieldNamesAndIds', () => { it('should return field names and ids', async () => { - mockExecuteFunctions.helpers.request.mockResolvedValue([ + mockExecuteFunctions.helpers.requestWithAuthentication.mockResolvedValue([ { id: 1, name: 'field1' }, { id: 2, name: 'field2' }, ]); - const result = await getFieldNamesAndIds.call(mockExecuteFunctions, '1', 'testJwt'); + const result = await getFieldNamesAndIds.call(mockExecuteFunctions, '1', 'baserowApi'); expect(result).toEqual({ names: ['field1', 'field2'], ids: ['field_1', 'field_2'], diff --git a/packages/nodes-base/nodes/Baserow/types.ts b/packages/nodes-base/nodes/Baserow/types.ts index 65b5b0a09d0..c9595141aca 100644 --- a/packages/nodes-base/nodes/Baserow/types.ts +++ b/packages/nodes-base/nodes/Baserow/types.ts @@ -1,6 +1,4 @@ export type BaserowCredentials = { - username: string; - password: string; host: string; }; @@ -28,10 +26,6 @@ export type LoadedResource = { type?: string; }; -export type Accumulator = { - [key: string]: string; -}; - export type Row = Record; export type FieldsUiValues = Array<{ @@ -39,4 +33,12 @@ export type FieldsUiValues = Array<{ fieldValue: string; }>; -export type Operation = 'create' | 'delete' | 'update' | 'get' | 'getAll'; +export type Operation = + | 'batchCreate' + | 'batchUpdate' + | 'batchDelete' + | 'create' + | 'delete' + | 'update' + | 'get' + | 'getAll'; diff --git a/packages/nodes-base/package.json b/packages/nodes-base/package.json index 39167bc8365..bb291f1f8d7 100644 --- a/packages/nodes-base/package.json +++ b/packages/nodes-base/package.json @@ -48,6 +48,7 @@ "dist/credentials/BambooHrApi.credentials.js", "dist/credentials/BannerbearApi.credentials.js", "dist/credentials/BaserowApi.credentials.js", + "dist/credentials/BaserowTokenApi.credentials.js", "dist/credentials/BeeminderApi.credentials.js", "dist/credentials/BeeminderOAuth2Api.credentials.js", "dist/credentials/BitbucketAccessTokenApi.credentials.js",