import { IExecuteFunctions, IHookFunctions, ILoadOptionsFunctions, IWebhookFunctions, IDataObject, IRequestOptions, IHttpRequestMethods, NodeApiError, NodeOperationError, } from 'n8n-workflow'; /** * Make an API request to Rettiwt */ export async function rettiwtApiRequest( this: IExecuteFunctions | ILoadOptionsFunctions | IHookFunctions | IWebhookFunctions, method: IHttpRequestMethods, resource: string, body: IDataObject = {}, query: IDataObject = {}, uri?: string, option: IDataObject = {}, ): Promise { const credentials = await this.getCredentials('rettiwtApi'); const apiKey = credentials.apiKey as string; // Prepare the request options const options: IRequestOptions = { method, headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${apiKey}`, }, body, qs: query, uri: uri || `https://api.rettiwt.com${resource}`, json: true, timeout: 10000, // 10 seconds timeout }; // Remove body or query if they're empty if (!Object.keys(body).length) { delete options.body; } if (!Object.keys(query).length) { delete options.qs; } try { // Make the request const response = await this.helpers.request(options); return response; } catch (error) { // Handle different types of errors if (error.statusCode === 401) { throw new NodeApiError(this.getNode(), error, { message: 'Invalid API key. Please check your credentials.', }); } if (error.statusCode === 403) { throw new NodeApiError(this.getNode(), error, { message: 'Access forbidden. Please check your API permissions.', }); } if (error.statusCode === 404) { throw new NodeApiError(this.getNode(), error, { message: 'Resource not found. Please check your request parameters.', }); } if (error.statusCode === 429) { throw new NodeApiError(this.getNode(), error, { message: 'Rate limit exceeded. Please try again later.', }); } if (error.statusCode >= 500) { throw new NodeApiError(this.getNode(), error, { message: 'Rettiwt API server error. Please try again later.', }); } if (error.response?.body?.message) { throw new NodeApiError(this.getNode(), error, { message: `Rettiwt API error: ${error.response.body.message}`, }); } // Generic error throw new NodeApiError(this.getNode(), error, { message: 'An error occurred while making the request to Rettiwt API.', }); } } /** * Handle errors that occur during API operations */ export function handleRettiwtApiError( this: IExecuteFunctions | ILoadOptionsFunctions | IHookFunctions | IWebhookFunctions, error: any, ): void { if (error instanceof NodeApiError) { throw error; } throw new NodeOperationError(this.getNode(), `Unexpected error: ${error.message}`); }