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

67 lines
1.6 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';
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
2019-11-10 14:14:36 -08:00
2019-11-06 22:06:19 -08:00
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-10 14:14:36 -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;
}
}
2019-11-08 07:41:10 -08:00
export function validateJSON(json: string | undefined): any { // tslint:disable-line:no-any
let result;
try {
result = JSON.parse(json!);
} catch (exception) {
result = [];
}
return result;
}
2019-11-10 14:14:36 -08:00
export function capitalize(s: string): string {
2019-11-08 07:41:10 -08:00
if (typeof s !== 'string') return '';
return s.charAt(0).toUpperCase() + s.slice(1);
}