n8n/packages/nodes-base/nodes/Autopilot/GenericFunctions.ts
Elias Meire 100d9bc087
refactor: Add IRequestOptions type to helpers.request for more type safety (no-changelog) (#8563)
Co-authored-by: कारतोफ्फेलस्क्रिप्ट™ <aditya@netroy.in>
2024-02-14 16:29:09 +01:00

79 lines
2 KiB
TypeScript

import type {
IExecuteFunctions,
ILoadOptionsFunctions,
IDataObject,
IHookFunctions,
IWebhookFunctions,
JsonObject,
IRequestOptions,
IHttpRequestMethods,
} from 'n8n-workflow';
import { NodeApiError } from 'n8n-workflow';
export async function autopilotApiRequest(
this: IExecuteFunctions | IWebhookFunctions | IHookFunctions | ILoadOptionsFunctions,
method: IHttpRequestMethods,
resource: string,
body: any = {},
query: IDataObject = {},
uri?: string,
_option: IDataObject = {},
): Promise<any> {
const credentials = (await this.getCredentials('autopilotApi')) as IDataObject;
const apiKey = `${credentials.apiKey}`;
const endpoint = 'https://api2.autopilothq.com/v1';
const options: IRequestOptions = {
headers: {
'Content-Type': 'application/json',
autopilotapikey: apiKey,
},
method,
body,
qs: query,
uri: uri || `${endpoint}${resource}`,
json: true,
};
if (!Object.keys(body as IDataObject).length) {
delete options.body;
}
if (!Object.keys(query).length) {
delete options.qs;
}
try {
return await this.helpers.request(options);
} catch (error) {
throw new NodeApiError(this.getNode(), error as JsonObject);
}
}
export async function autopilotApiRequestAllItems(
this: IExecuteFunctions | ILoadOptionsFunctions,
propertyName: string,
method: IHttpRequestMethods,
endpoint: string,
body: any = {},
query: IDataObject = {},
): Promise<any> {
const returnData: IDataObject[] = [];
const returnAll = this.getNodeParameter('returnAll', 0, false) as boolean;
const base = endpoint;
let responseData;
do {
responseData = await autopilotApiRequest.call(this, method, endpoint, body, query);
endpoint = `${base}/${responseData.bookmark}`;
returnData.push.apply(returnData, responseData[propertyName] as IDataObject[]);
const limit = query.limit as number | undefined;
if (limit && returnData.length >= limit && !returnAll) {
return returnData;
}
} while (responseData.bookmark !== undefined);
return returnData;
}