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

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

66 lines
1.5 KiB
TypeScript
Raw Normal View History

import type {
IExecuteFunctions,
ILoadOptionsFunctions,
IDataObject,
IHookFunctions,
IWebhookFunctions,
JsonObject,
IHttpRequestMethods,
IRequestOptions,
} from 'n8n-workflow';
import { NodeApiError } from 'n8n-workflow';
2020-04-26 12:56:50 -07:00
import { snakeCase } from 'change-case';
2020-04-26 12:56:50 -07:00
export async function bannerbearApiRequest(
this: IExecuteFunctions | IWebhookFunctions | IHookFunctions | ILoadOptionsFunctions,
method: IHttpRequestMethods,
resource: string,
body: any = {},
query: IDataObject = {},
uri?: string,
headers: IDataObject = {},
): Promise<any> {
const credentials = await this.getCredentials('bannerbearApi');
2020-04-26 12:56:50 -07:00
const options: IRequestOptions = {
2020-04-26 12:56:50 -07:00
headers: {
Accept: 'application/json',
Authorization: `Bearer ${credentials.apiKey}`,
},
method,
body,
qs: query,
uri: uri || `https://api.bannerbear.com/v2${resource}`,
2020-04-26 12:56:50 -07:00
json: true,
};
if (!Object.keys(body as IDataObject).length) {
2020-04-26 12:56:50 -07:00
delete options.form;
}
if (!Object.keys(query).length) {
delete options.qs;
}
options.headers = Object.assign({}, options.headers, headers);
try {
return await this.helpers.request(options);
2020-04-26 12:56:50 -07:00
} catch (error) {
throw new NodeApiError(this.getNode(), error as JsonObject);
2020-04-26 12:56:50 -07:00
}
}
export function keysToSnakeCase(elements: IDataObject[] | IDataObject): IDataObject[] {
2020-04-26 12:56:50 -07:00
if (!Array.isArray(elements)) {
elements = [elements];
}
for (const element of elements) {
for (const key of Object.keys(element)) {
if (key !== snakeCase(key)) {
element[snakeCase(key)] = element[key];
delete element[key];
}
}
}
return elements;
}