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

53 lines
1.3 KiB
TypeScript
Raw Normal View History

2019-11-06 16:58:18 -08:00
import { OptionsWithUri } from 'request';
import {
IExecuteFunctions,
IHookFunctions,
ILoadOptionsFunctions,
2019-11-06 22:06:19 -08:00
IExecuteSingleFunctions,
BINARY_ENCODING
2019-11-06 16:58:18 -08:00
} from 'n8n-core';
import * as _ from 'lodash';
import { IDataObject } from 'n8n-workflow';
2019-11-06 22:06:19 -08:00
export async function freshdeskApiRequest(this: IHookFunctions | IExecuteFunctions | IExecuteSingleFunctions | ILoadOptionsFunctions, resource: string, method: string, body: any = {}, headers?: object): Promise<any> { // tslint:disable-line:no-any
const credentials = this.getCredentials('freshdeskApi');
2019-11-06 16:58:18 -08:00
if (credentials === undefined) {
throw new Error('No credentials got returned!');
}
2019-11-07 10:07:29 -08:00
const apiKey = `${credentials.apiKey}:X`;
2019-11-06 16:58:18 -08:00
2019-11-07 10:07:29 -08:00
const headerWithAuthentication = Object.assign({}, headers, { Authorization: `${Buffer.from(apiKey).toString(BINARY_ENCODING)}` });
2019-11-06 22:06:19 -08:00
const endpoint = 'freshdesk.com/api/v2/';
2019-11-06 16:58:18 -08:00
const options: OptionsWithUri = {
2019-11-06 22:06:19 -08:00
headers: headerWithAuthentication,
2019-11-06 16:58:18 -08:00
method,
2019-11-06 22:06:19 -08:00
body,
uri: `https://${credentials.domain}.${endpoint}${resource}`,
2019-11-06 16:58:18 -08:00
json: true
};
2019-11-06 22:06:19 -08:00
if (_.isEmpty(options.body)) {
2019-11-07 10:07:29 -08:00
delete options.body;
2019-11-06 22:06:19 -08:00
}
2019-11-06 16:58:18 -08:00
try {
return await this.helpers.request!(options);
} catch (error) {
console.error(error);
const errorMessage = error.response.body.message || error.response.body.Message;
if (errorMessage !== undefined) {
throw errorMessage;
}
throw error.response.body;
}
}