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

82 lines
2.1 KiB
TypeScript
Raw Normal View History

2019-12-03 13:48:17 -08:00
import { OptionsWithUri } from 'request';
import {
IExecuteFunctions,
IHookFunctions,
ILoadOptionsFunctions,
IExecuteSingleFunctions
} from 'n8n-core';
import {
IDataObject,
} from 'n8n-workflow';
export async function hubspotApiRequest(this: IHookFunctions | IExecuteFunctions | IExecuteSingleFunctions | ILoadOptionsFunctions, method: string, endpoint: string, body: any = {}, query: IDataObject = {}, uri?: string): Promise<any> { // tslint:disable-line:no-any
2020-03-08 19:39:20 -07:00
let credentials;
try {
credentials = this.getCredentials('hubspotApi');
} catch (exception) {
credentials = this.getCredentials('hubspotDeveloperApi');
2019-12-03 13:48:17 -08:00
}
2020-03-08 19:39:20 -07:00
query!.hapikey = credentials!.apiKey as string;
2019-12-03 13:48:17 -08:00
const options: OptionsWithUri = {
method,
qs: query,
uri: uri || `https://api.hubapi.com${endpoint}`,
body,
2019-12-04 09:21:02 -08:00
json: true,
useQuerystring: true,
2019-12-03 13:48:17 -08:00
};
try {
return await this.helpers.request!(options);
} catch (error) {
2020-03-08 19:39:20 -07:00
console.log(error)
2019-12-03 13:48:17 -08:00
const errorMessage = error.response.body.message || error.response.body.Message;
if (errorMessage !== undefined) {
throw errorMessage;
}
throw error.response.body;
}
}
/**
* Make an API request to paginated hubspot endpoint
* and return all results
*/
export async function hubspotApiRequestAllItems(this: IHookFunctions | IExecuteFunctions | ILoadOptionsFunctions, propertyName: string, method: string, endpoint: string, body: any = {}, query: IDataObject = {}): Promise<any> { // tslint:disable-line:no-any
const returnData: IDataObject[] = [];
let responseData;
query.limit = 250;
query.count = 100;
do {
responseData = await hubspotApiRequest.call(this, method, endpoint, body, query);
query.offset = responseData.offset;
query['vid-offset'] = responseData['vid-offset'];
returnData.push.apply(returnData, responseData[propertyName]);
} while (
responseData['has-more'] !== undefined &&
responseData['has-more'] !== null &&
responseData['has-more'] !== false
);
return returnData;
}
export function validateJSON(json: string | undefined): any { // tslint:disable-line:no-any
let result;
try {
result = JSON.parse(json!);
} catch (exception) {
result = '';
}
return result;
}