import type { IDataObject, IExecuteFunctions, ILoadOptionsFunctions, IHttpRequestMethods, JsonObject, } from 'n8n-workflow'; import { NodeApiError } from 'n8n-workflow'; import { URL } from 'url'; export async function pexelsApiRequest( this: IExecuteFunctions | ILoadOptionsFunctions, method: IHttpRequestMethods, endpoint: string, body: IDataObject = {}, qs: IDataObject = {}, ) { const credentials = await this.getCredentials('pexelsApi'); const baseUrl = ((credentials?.baseUrl as string) || 'https://api.pexels.com').replace(/\/+$/, ''); const requestOptions = { method, uri: `${baseUrl}/${endpoint.replace(/^\/+/, '')}`, body, qs, json: true, }; if (!Object.keys(body).length) { delete (requestOptions as IDataObject).body; } if (!Object.keys(qs).length) { delete (requestOptions as IDataObject).qs; } try { return await this.helpers.requestWithAuthentication.call(this, 'pexelsApi', requestOptions); } catch (error) { throw new NodeApiError(this.getNode(), error as JsonObject); } } export async function pexelsApiRequestAllItems( this: IExecuteFunctions, propertyName: string, method: IHttpRequestMethods, endpoint: string, body: IDataObject = {}, qs: IDataObject = {}, limit = 0, ): Promise { const returnData: IDataObject[] = []; let page = Number(qs.page) || 1; if (!qs.per_page) { qs.per_page = limit && limit < 80 ? limit : 80; } while (true) { qs.page = page; const responseData = await pexelsApiRequest.call(this, method, endpoint, body, qs); const values = ((responseData as IDataObject)[propertyName] as IDataObject[]) || []; returnData.push(...values); if (limit && returnData.length >= limit) { return returnData.slice(0, limit); } const nextPageUrl = (responseData as IDataObject).next_page as string | undefined; if (!nextPageUrl) break; try { const parsed = new URL(nextPageUrl); const nextPage = parsed.searchParams.get('page'); if (!nextPage) break; page = Number(nextPage); if (Number.isNaN(page)) break; } catch (error) { // If next_page is not a URL, stop pagination to avoid an endless loop break; } } return returnData; }