mirror of
https://github.com/n8n-io/n8n.git
synced 2024-12-25 04:34:06 -08:00
1d27a9e87e
* 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 * 🚧 create basic setup NodeError * 🚧 add httpCodes * 🚧 add path priolist * 🚧 handle statusCode in error, adjust interfaces * 🚧 fixing type issues w/Ivan * 🚧 add error exploration * 👔 fix linter issues * 🔧 improve object check * 🚧 remove path passing from NodeApiError * 🚧 add multi error + refactor findProperty method * 👔 allow any * 🔧 handle multi error message callback * ⚡ change return type of callback * ⚡ add customCallback to MultiError * 🚧 refactor to use INode * 🔨 handle arrays, continue search after first null property found * 🚫 refactor method access * 🚧 setup NodeErrorView * ⚡ change timestamp to Date.now * 📚 Add documentation for methods and constants * 🚧 change message setting * 🚚 move NodeErrors to workflow * ✨ add new ErrorView for Nodes * 🎨 improve error notification * 🎨 refactor interfaces * ⚡ add WorkflowOperationError, refactor error throwing * 👕 fix linter issues * 🎨 rename param * 🐛 fix handling normal errors * ⚡ add usage of NodeApiError * 🎨 fix throw new error instead of constructor * 🎨 remove unnecessary code/comments * 🎨 adjusted spacing + updated status messages * 🎨 fix tab indentation * ✨ Replace current errors with custom errors (#1576) * ⚡ Introduce NodeApiError in catch blocks * ⚡ Introduce NodeOperationError in nodes * ⚡ Add missing errors and remove incompatible * ⚡ Fix NodeOperationError in incompatible nodes * 🔧 Adjust error handling in missed nodes PayPal, FileMaker, Reddit, Taiga and Facebook Graph API nodes * 🔨 Adjust Strava Trigger node error handling * 🔨 Adjust AWS nodes error handling * 🔨 Remove duplicate instantiation of NodeApiError * 🐛 fix strava trigger node error handling * Add XML parsing to NodeApiError constructor (#1633) * 🐛 Remove type annotation from catch variable * ✨ Add XML parsing to NodeApiError * ⚡ Simplify error handling in Rekognition node * ⚡ Pass in XML flag in generic functions * 🔥 Remove try/catch wrappers at call sites * 🔨 Refactor setting description from XML * 🔨 Refactor let to const in resource loaders * ⚡ Find property in parsed XML * ⚡ Change let to const * 🔥 Remove unneeded try/catch block * 👕 Fix linting issues * 🐛 Fix errors from merge conflict resolution * ⚡ Add custom errors to latest contributions * 👕 Fix linting issues * ⚡ Refactor MongoDB helpers for custom errors * 🐛 Correct custom error type * ⚡ Apply feedback to A nodes * ⚡ Apply feedback to missed A node * ⚡ Apply feedback to B-D nodes * ⚡ Apply feedback to E-F nodes * ⚡ Apply feedback to G nodes * ⚡ Apply feedback to H-L nodes * ⚡ Apply feedback to M nodes * ⚡ Apply feedback to P nodes * ⚡ Apply feedback to R nodes * ⚡ Apply feedback to S nodes * ⚡ Apply feedback to T nodes * ⚡ Apply feedback to V-Z nodes * ⚡ Add HTTP code to iterable node error * 🔨 Standardize e as error * 🔨 Standardize err as error * ⚡ 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>
190 lines
6.1 KiB
TypeScript
190 lines
6.1 KiB
TypeScript
import {
|
|
OptionsWithUri,
|
|
} from 'request';
|
|
|
|
import {
|
|
IExecuteFunctions,
|
|
IExecuteSingleFunctions,
|
|
ILoadOptionsFunctions,
|
|
} from 'n8n-core';
|
|
|
|
import {
|
|
IDataObject,
|
|
INodePropertyOptions,
|
|
NodeApiError,
|
|
} from 'n8n-workflow';
|
|
|
|
import * as moment from 'moment-timezone';
|
|
|
|
import * as jwt from 'jsonwebtoken';
|
|
|
|
export async function salesforceApiRequest(this: IExecuteFunctions | IExecuteSingleFunctions | ILoadOptionsFunctions, method: string, endpoint: string, body: any = {}, qs: IDataObject = {}, uri?: string, option: IDataObject = {}): Promise<any> { // tslint:disable-line:no-any
|
|
const authenticationMethod = this.getNodeParameter('authentication', 0, 'oAuth2') as string;
|
|
|
|
try {
|
|
if (authenticationMethod === 'jwt') {
|
|
// https://help.salesforce.com/articleView?id=remoteaccess_oauth_jwt_flow.htm&type=5
|
|
const credentialsType = 'salesforceJwtApi';
|
|
const credentials = this.getCredentials(credentialsType);
|
|
const response = await getAccessToken.call(this, credentials as IDataObject);
|
|
const { instance_url, access_token } = response;
|
|
const options = getOptions.call(this, method, (uri || endpoint), body, qs, instance_url as string);
|
|
options.headers!.Authorization = `Bearer ${access_token}`;
|
|
//@ts-ignore
|
|
return await this.helpers.request(options);
|
|
} else {
|
|
// https://help.salesforce.com/articleView?id=remoteaccess_oauth_web_server_flow.htm&type=5
|
|
const credentialsType = 'salesforceOAuth2Api';
|
|
const credentials = this.getCredentials(credentialsType);
|
|
const subdomain = ((credentials!.accessTokenUrl as string).match(/https:\/\/(.+).salesforce\.com/) || [])[1];
|
|
const options = getOptions.call(this, method, (uri || endpoint), body, qs, `https://${subdomain}.salesforce.com`);
|
|
//@ts-ignore
|
|
return await this.helpers.requestOAuth2.call(this, credentialsType, options);
|
|
}
|
|
} catch (error) {
|
|
throw new NodeApiError(this.getNode(), error);
|
|
}
|
|
}
|
|
|
|
export async function salesforceApiRequestAllItems(this: IExecuteFunctions | ILoadOptionsFunctions, propertyName: string, method: string, endpoint: string, body: any = {}, query: IDataObject = {}): Promise<any> { // tslint:disable-line:no-any
|
|
const returnData: IDataObject[] = [];
|
|
|
|
let responseData;
|
|
let uri: string | undefined;
|
|
|
|
do {
|
|
responseData = await salesforceApiRequest.call(this, method, endpoint, body, query, uri);
|
|
uri = `${endpoint}/${responseData.nextRecordsUrl?.split('/')?.pop()}`;
|
|
returnData.push.apply(returnData, responseData[propertyName]);
|
|
} while (
|
|
responseData.nextRecordsUrl !== undefined &&
|
|
responseData.nextRecordsUrl !== null
|
|
);
|
|
|
|
return returnData;
|
|
}
|
|
|
|
/**
|
|
* Sorts the given options alphabetically
|
|
*
|
|
* @export
|
|
* @param {INodePropertyOptions[]} options
|
|
* @returns {INodePropertyOptions[]}
|
|
*/
|
|
export function sortOptions(options: INodePropertyOptions[]): void {
|
|
options.sort((a, b) => {
|
|
if (a.name < b.name) { return -1; }
|
|
if (a.name > b.name) { return 1; }
|
|
return 0;
|
|
});
|
|
}
|
|
|
|
function getOptions(this: IExecuteFunctions | IExecuteSingleFunctions | ILoadOptionsFunctions, method: string, endpoint: string, body: any, qs: IDataObject, instanceUrl: string): OptionsWithUri { // tslint:disable-line:no-any
|
|
const options: OptionsWithUri = {
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
},
|
|
method,
|
|
body: method === 'GET' ? undefined : body,
|
|
qs,
|
|
uri: `${instanceUrl}/services/data/v39.0${endpoint}`,
|
|
json: true,
|
|
};
|
|
|
|
//@ts-ignore
|
|
return options;
|
|
}
|
|
|
|
function getAccessToken(this: IExecuteFunctions | IExecuteSingleFunctions | ILoadOptionsFunctions, credentials: IDataObject): Promise<IDataObject> {
|
|
const now = moment().unix();
|
|
const authUrl = credentials.environment === 'sandbox' ? 'https://test.salesforce.com' : 'https://login.salesforce.com';
|
|
|
|
const signature = jwt.sign(
|
|
{
|
|
'iss': credentials.clientId as string,
|
|
'sub': credentials.username as string,
|
|
'aud': authUrl,
|
|
'exp': now + 3 * 60,
|
|
},
|
|
credentials.privateKey as string,
|
|
{
|
|
algorithm: 'RS256',
|
|
header: {
|
|
'alg': 'RS256',
|
|
},
|
|
},
|
|
);
|
|
|
|
const options: OptionsWithUri = {
|
|
headers: {
|
|
'Content-Type': 'application/x-www-form-urlencoded',
|
|
},
|
|
method: 'POST',
|
|
form: {
|
|
grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
|
|
assertion: signature,
|
|
},
|
|
uri: `${authUrl}/services/oauth2/token`,
|
|
json: true,
|
|
};
|
|
|
|
//@ts-ignore
|
|
return this.helpers.request(options);
|
|
}
|
|
|
|
export function getConditions(options: IDataObject) {
|
|
const conditions = (options.conditionsUi as IDataObject || {}).conditionValues as IDataObject[];
|
|
let data = undefined;
|
|
if (Array.isArray(conditions) && conditions.length !== 0) {
|
|
data = conditions.map((condition: IDataObject) => `${condition.field}${(condition.operation) === 'equal' ? '=' : condition.operation}${getValue(condition.value)}`);
|
|
data = `WHERE ${data.join(' AND ')}`;
|
|
}
|
|
return data;
|
|
}
|
|
|
|
export function getDefaultFields(sobject: string) {
|
|
return (
|
|
{
|
|
'Account': 'id,name,type',
|
|
'Lead': 'id,company,firstname,lastname,street,postalCode,city,email,status',
|
|
'Contact': 'id,firstname,lastname,email',
|
|
'Opportunity': 'id,accountId,amount,probability,type',
|
|
'Case': 'id,accountId,contactId,priority,status,subject,type',
|
|
'Task': 'id,subject,status,priority',
|
|
'Attachment': 'id,name',
|
|
'User': 'id,name,email',
|
|
} as IDataObject
|
|
)[sobject];
|
|
}
|
|
|
|
export function getQuery(options: IDataObject, sobject: string, returnAll: boolean, limit = 0) {
|
|
const fields: string[] = [];
|
|
if (options.fields) {
|
|
// options.fields is comma separated in standard Salesforce objects and array in custom Salesforce objects -- handle both cases
|
|
if (typeof options.fields === 'string') {
|
|
fields.push.apply(fields, options.fields.split(','));
|
|
} else {
|
|
fields.push.apply(fields, options.fields as string[]);
|
|
}
|
|
} else {
|
|
fields.push.apply(fields, (getDefaultFields(sobject) as string || 'id').split(','));
|
|
}
|
|
const conditions = getConditions(options);
|
|
|
|
let query = `SELECT ${fields.join(',')} FROM ${sobject} ${(conditions ? conditions : '')}`;
|
|
|
|
if (returnAll === false) {
|
|
query = `SELECT ${fields.join(',')} FROM ${sobject} ${(conditions ? conditions : '')} LIMIT ${limit}`;
|
|
}
|
|
|
|
return query;
|
|
}
|
|
|
|
export function getValue(value: any) { // tslint:disable-line:no-any
|
|
if (typeof value === 'string') {
|
|
return `'${value}'`;
|
|
} else {
|
|
return value;
|
|
}
|
|
}
|