n8n/packages/nodes-base/nodes/InvoiceNinja/GenericFunctions.ts
Omar Ajoue d3fecb9f6d
🎨 Centralize error throwing for encryption keys and credentials (#3105)
* Centralized error throwing for encryption key

* Unifying the error message used by cli and core packages

* Improvements to error messages to make it more DRY

* Removed unnecessary throw

* Throwing error when credential does not exist to simplify node behavior (#3112)

Co-authored-by: Iván Ovejero <ivov.src@gmail.com>
2022-04-15 08:00:47 +02:00

66 lines
1.8 KiB
TypeScript

import {
OptionsWithUri,
} from 'request';
import {
IExecuteFunctions,
IExecuteSingleFunctions,
IHookFunctions,
ILoadOptionsFunctions,
} from 'n8n-core';
import {
IDataObject, NodeApiError, NodeOperationError,
} from 'n8n-workflow';
import {
get,
} from 'lodash';
export async function invoiceNinjaApiRequest(this: IHookFunctions | IExecuteFunctions | IExecuteSingleFunctions | ILoadOptionsFunctions, method: string, endpoint: string, body: any = {}, query?: IDataObject, uri?: string): Promise<any> { // tslint:disable-line:no-any
const credentials = await this.getCredentials('invoiceNinjaApi');
const baseUrl = credentials!.url || 'https://app.invoiceninja.com';
const options: OptionsWithUri = {
headers: {
Accept: 'application/json',
'X-Ninja-Token': credentials.apiToken,
},
method,
qs: query,
uri: uri || `${baseUrl}/api/v1${endpoint}`,
body,
json: true,
};
try {
return await this.helpers.request!(options);
} catch (error) {
throw new NodeApiError(this.getNode(), error);
}
}
export async function invoiceNinjaApiRequestAllItems(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;
query.per_page = 100;
do {
responseData = await invoiceNinjaApiRequest.call(this, method, endpoint, body, query, uri);
const next = get(responseData, 'meta.pagination.links.next') as string | undefined;
if (next) {
uri = next;
}
returnData.push.apply(returnData, responseData[propertyName]);
} while (
responseData.meta !== undefined &&
responseData.meta.pagination &&
responseData.meta.pagination.links &&
responseData.meta.pagination.links.next
);
return returnData;
}