n8n/packages/nodes-base/nodes/FileMaker/GenericFunctions.ts

366 lines
9.7 KiB
TypeScript
Raw Normal View History

import type { IExecuteFunctions, IExecuteSingleFunctions, ILoadOptionsFunctions } from 'n8n-core';
2019-11-09 16:54:25 -08:00
import type { IDataObject, INodePropertyOptions } from 'n8n-workflow';
import { NodeApiError, NodeOperationError } from 'n8n-workflow';
2019-11-09 16:54:25 -08:00
import type { OptionsWithUri } from 'request';
interface ScriptsOptions {
script?: any;
'script.param'?: any;
'script.prerequest'?: any;
'script.prerequest.param'?: any;
'script.presort'?: any;
'script.presort.param'?: any;
}
interface LayoutObject {
name: string;
isFolder?: boolean;
folderLayoutNames?: LayoutObject[];
}
2019-11-14 04:02:57 -08:00
interface ScriptObject {
name: string;
isFolder?: boolean;
folderScriptNames?: LayoutObject[];
}
export async function getToken(
this: ILoadOptionsFunctions | IExecuteFunctions | IExecuteSingleFunctions,
): Promise<any> {
const credentials = await this.getCredentials('fileMaker');
2019-11-09 16:54:25 -08:00
const host = credentials.host as string;
const db = credentials.db as string;
const login = credentials.login as string;
const password = credentials.password as string;
2019-11-09 16:54:25 -08:00
const url = `https://${host}/fmi/data/v1/databases/${db}/sessions`;
// Reset all values
const requestOptions: OptionsWithUri = {
2019-11-09 16:54:25 -08:00
uri: url,
headers: {},
method: 'POST',
2020-10-22 06:46:03 -07:00
json: true,
//rejectUnauthorized: !this.getNodeParameter('allowUnauthorizedCerts', itemIndex, false) as boolean,
};
requestOptions.auth = {
user: login,
pass: password,
};
requestOptions.body = {
fmDataSource: [
{
database: host,
username: login,
password,
},
],
2019-11-09 16:54:25 -08:00
};
try {
const response = await this.helpers.request(requestOptions);
if (typeof response === 'string') {
throw new NodeOperationError(
this.getNode(),
'Response body is not valid JSON. Change "Response Format" to "String"',
);
}
return response.response.token;
2019-11-09 16:54:25 -08:00
} catch (error) {
:sparkles: 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 * :construction: create basic setup NodeError * :construction: add httpCodes * :construction: add path priolist * :construction: handle statusCode in error, adjust interfaces * :construction: fixing type issues w/Ivan * :construction: add error exploration * 👔 fix linter issues * :wrench: improve object check * :construction: remove path passing from NodeApiError * :construction: add multi error + refactor findProperty method * 👔 allow any * :wrench: handle multi error message callback * :zap: change return type of callback * :zap: add customCallback to MultiError * :construction: refactor to use INode * :hammer: handle arrays, continue search after first null property found * 🚫 refactor method access * :construction: setup NodeErrorView * :zap: change timestamp to Date.now * :books: Add documentation for methods and constants * :construction: change message setting * 🚚 move NodeErrors to workflow * :sparkles: add new ErrorView for Nodes * :art: improve error notification * :art: refactor interfaces * :zap: add WorkflowOperationError, refactor error throwing * 👕 fix linter issues * :art: rename param * :bug: fix handling normal errors * :zap: add usage of NodeApiError * :art: fix throw new error instead of constructor * :art: remove unnecessary code/comments * :art: adjusted spacing + updated status messages * :art: fix tab indentation * ✨ Replace current errors with custom errors (#1576) * :zap: Introduce NodeApiError in catch blocks * :zap: Introduce NodeOperationError in nodes * :zap: Add missing errors and remove incompatible * :zap: Fix NodeOperationError in incompatible nodes * :wrench: Adjust error handling in missed nodes PayPal, FileMaker, Reddit, Taiga and Facebook Graph API nodes * :hammer: Adjust Strava Trigger node error handling * :hammer: Adjust AWS nodes error handling * :hammer: Remove duplicate instantiation of NodeApiError * :bug: fix strava trigger node error handling * Add XML parsing to NodeApiError constructor (#1633) * :bug: Remove type annotation from catch variable * :sparkles: Add XML parsing to NodeApiError * :zap: Simplify error handling in Rekognition node * :zap: Pass in XML flag in generic functions * :fire: Remove try/catch wrappers at call sites * :hammer: Refactor setting description from XML * :hammer: Refactor let to const in resource loaders * :zap: Find property in parsed XML * :zap: Change let to const * :fire: Remove unneeded try/catch block * :shirt: Fix linting issues * :bug: Fix errors from merge conflict resolution * :zap: Add custom errors to latest contributions * :shirt: Fix linting issues * :zap: Refactor MongoDB helpers for custom errors * :bug: Correct custom error type * :zap: Apply feedback to A nodes * :zap: Apply feedback to missed A node * :zap: Apply feedback to B-D nodes * :zap: Apply feedback to E-F nodes * :zap: Apply feedback to G nodes * :zap: Apply feedback to H-L nodes * :zap: Apply feedback to M nodes * :zap: Apply feedback to P nodes * :zap: Apply feedback to R nodes * :zap: Apply feedback to S nodes * :zap: Apply feedback to T nodes * :zap: Apply feedback to V-Z nodes * :zap: Add HTTP code to iterable node error * :hammer: Standardize e as error * :hammer: Standardize err as error * :zap: 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 09:33:36 -07:00
throw new NodeApiError(this.getNode(), error);
2019-11-09 16:54:25 -08:00
}
}
function parseLayouts(layouts: LayoutObject[]): INodePropertyOptions[] {
const returnData: INodePropertyOptions[] = [];
for (const layout of layouts) {
if (layout.isFolder!) {
returnData.push(...parseLayouts(layout.folderLayoutNames!));
} else {
returnData.push({
name: layout.name,
value: layout.name,
});
}
}
return returnData;
}
2019-11-09 16:54:25 -08:00
/**
* Make an API request to ActiveCampaign
*
*/
export async function layoutsApiRequest(
this: ILoadOptionsFunctions | IExecuteFunctions | IExecuteSingleFunctions,
): Promise<INodePropertyOptions[]> {
2019-11-09 16:54:25 -08:00
const token = await getToken.call(this);
const credentials = await this.getCredentials('fileMaker');
2019-11-09 16:54:25 -08:00
const host = credentials.host as string;
const db = credentials.db as string;
const url = `https://${host}/fmi/data/v1/databases/${db}/layouts`;
2019-11-09 16:54:25 -08:00
const options: OptionsWithUri = {
headers: {
Authorization: `Bearer ${token}`,
2019-11-09 16:54:25 -08:00
},
method: 'GET',
uri: url,
2020-10-22 06:46:03 -07:00
json: true,
2019-11-09 16:54:25 -08:00
};
try {
const responseData = await this.helpers.request(options);
const items = parseLayouts(responseData.response.layouts);
items.sort((a, b) => (a.name > b.name ? 0 : 1));
return items;
2019-11-09 16:54:25 -08:00
} catch (error) {
throw new NodeApiError(this.getNode(), error);
2019-11-09 16:54:25 -08:00
}
}
2019-11-09 18:14:10 -08:00
/**
* Make an API request to ActiveCampaign
*
*/
export async function getFields(this: ILoadOptionsFunctions): Promise<any> {
2019-11-09 18:14:10 -08:00
const token = await getToken.call(this);
const credentials = await this.getCredentials('fileMaker');
2019-11-09 18:14:10 -08:00
const layout = this.getCurrentNodeParameter('layout') as string;
const host = credentials.host as string;
const db = credentials.db as string;
const url = `https://${host}/fmi/data/v1/databases/${db}/layouts/${layout}`;
const options: OptionsWithUri = {
headers: {
Authorization: `Bearer ${token}`,
2019-11-09 18:14:10 -08:00
},
method: 'GET',
uri: url,
2020-10-22 06:46:03 -07:00
json: true,
2019-11-09 18:14:10 -08:00
};
try {
const responseData = await this.helpers.request(options);
return responseData.response.fieldMetaData;
2019-11-09 18:14:10 -08:00
} catch (error) {
// If that data does not exist for some reason return the actual error
throw error;
}
}
/**
* Make an API request to ActiveCampaign
*
*/
export async function getPortals(this: ILoadOptionsFunctions): Promise<any> {
const token = await getToken.call(this);
const credentials = await this.getCredentials('fileMaker');
const layout = this.getCurrentNodeParameter('layout') as string;
const host = credentials.host as string;
const db = credentials.db as string;
const url = `https://${host}/fmi/data/v1/databases/${db}/layouts/${layout}`;
const options: OptionsWithUri = {
headers: {
Authorization: `Bearer ${token}`,
},
method: 'GET',
uri: url,
2020-10-22 06:46:03 -07:00
json: true,
};
try {
const responseData = await this.helpers.request(options);
return responseData.response.portalMetaData;
} catch (error) {
// If that data does not exist for some reason return the actual error
throw error;
}
}
function parseScriptsList(scripts: ScriptObject[]): INodePropertyOptions[] {
const returnData: INodePropertyOptions[] = [];
for (const script of scripts) {
if (script.isFolder!) {
returnData.push(...parseScriptsList(script.folderScriptNames!));
} else if (script.name !== '-') {
returnData.push({
name: script.name,
value: script.name,
});
}
}
return returnData;
}
/**
* Make an API request to ActiveCampaign
*
*/
export async function getScripts(this: ILoadOptionsFunctions): Promise<any> {
const token = await getToken.call(this);
const credentials = await this.getCredentials('fileMaker');
2019-11-09 16:54:25 -08:00
const host = credentials.host as string;
const db = credentials.db as string;
const url = `https://${host}/fmi/data/v1/databases/${db}/scripts`;
const options: OptionsWithUri = {
headers: {
Authorization: `Bearer ${token}`,
},
method: 'GET',
2019-11-09 16:54:25 -08:00
uri: url,
2020-10-22 06:46:03 -07:00
json: true,
2019-11-09 16:54:25 -08:00
};
try {
const responseData = await this.helpers.request(options);
const items = parseScriptsList(responseData.response.scripts);
items.sort((a, b) => (a.name > b.name ? 0 : 1));
return items;
2019-11-09 16:54:25 -08:00
} catch (error) {
// If that data does not exist for some reason return the actual error
throw error;
2019-11-09 16:54:25 -08:00
}
}
export async function logout(
this: ILoadOptionsFunctions | IExecuteFunctions | IExecuteSingleFunctions,
token: string,
): Promise<any> {
const credentials = await this.getCredentials('fileMaker');
2019-11-09 16:54:25 -08:00
const host = credentials.host as string;
const db = credentials.db as string;
const url = `https://${host}/fmi/data/v1/databases/${db}/sessions/${token}`;
// Reset all values
const requestOptions: OptionsWithUri = {
2019-11-09 16:54:25 -08:00
uri: url,
headers: {},
method: 'DELETE',
2020-10-22 06:46:03 -07:00
json: true,
2019-11-09 16:54:25 -08:00
//rejectUnauthorized: !this.getNodeParameter('allowUnauthorizedCerts', itemIndex, false) as boolean,
};
try {
const response = await this.helpers.request(requestOptions);
2019-11-09 16:54:25 -08:00
if (typeof response === 'string') {
throw new NodeOperationError(
this.getNode(),
'Response body is not valid JSON. Change "Response Format" to "String"',
);
2019-11-09 16:54:25 -08:00
}
return response;
} catch (error) {
const errorMessage = `${error.response.body.messages[0].message}'(' + ${error.response.body.messages[0].message}')'`;
2019-11-09 16:54:25 -08:00
if (errorMessage !== undefined) {
throw new Error(errorMessage);
2019-11-09 16:54:25 -08:00
}
throw error.response.body;
}
}
export function parseSort(this: IExecuteFunctions, i: number): object | null {
let sort;
const setSort = this.getNodeParameter('setSort', i, false);
if (!setSort) {
sort = null;
} else {
sort = [];
const sortParametersUi = this.getNodeParameter('sortParametersUi', i, {}) as IDataObject;
if (sortParametersUi.rules !== undefined) {
for (const parameterData of sortParametersUi.rules as IDataObject[]) {
sort.push({
fieldName: parameterData.name as string,
sortOrder: parameterData.value,
});
}
}
}
return sort;
}
export function parseScripts(this: IExecuteFunctions, i: number): object | null {
const setScriptAfter = this.getNodeParameter('setScriptAfter', i, false);
const setScriptBefore = this.getNodeParameter('setScriptBefore', i, false);
const setScriptSort = this.getNodeParameter('setScriptSort', i, false);
if (!setScriptAfter && setScriptBefore && setScriptSort) {
return {};
} else {
const scripts = {} as ScriptsOptions;
if (setScriptAfter) {
scripts.script = this.getNodeParameter('scriptAfter', i);
scripts['script.param'] = this.getNodeParameter('scriptAfter', i);
}
if (setScriptBefore) {
scripts['script.prerequest'] = this.getNodeParameter('scriptBefore', i);
scripts['script.prerequest.param'] = this.getNodeParameter('scriptBeforeParam', i);
}
if (setScriptSort) {
scripts['script.presort'] = this.getNodeParameter('scriptSort', i);
scripts['script.presort.param'] = this.getNodeParameter('scriptSortParam', i);
}
return scripts;
}
}
export function parsePortals(this: IExecuteFunctions, i: number): object | null {
let portals;
const getPortalsData = this.getNodeParameter('getPortals', i);
if (!getPortalsData) {
portals = [];
} else {
portals = this.getNodeParameter('portals', i);
}
return portals as IDataObject;
}
export function parseQuery(this: IExecuteFunctions, i: number): object | null {
let queries;
const queriesParamUi = this.getNodeParameter('queries', i, {}) as IDataObject;
if (queriesParamUi.query !== undefined) {
queries = [];
for (const queryParam of queriesParamUi.query as IDataObject[]) {
const query: IDataObject = {
omit: queryParam.omit ? 'true' : 'false',
};
for (const field of (queryParam.fields as IDataObject).field as IDataObject[]) {
query[field.name as string] = field.value;
}
queries.push(query);
}
} else {
queries = null;
}
return queries;
}
export function parseFields(this: IExecuteFunctions, i: number): object | null {
let fieldData: IDataObject | null;
const fieldsParametersUi = this.getNodeParameter('fieldsParametersUi', i, {}) as IDataObject;
if (fieldsParametersUi.fields !== undefined) {
fieldData = {};
for (const field of fieldsParametersUi.fields as IDataObject[]) {
fieldData[field.name as string] = field.value;
}
} else {
fieldData = null;
}
return fieldData;
}