UNPKG

n8n-nodes-zid

Version:

BETA; n8n custom nodes for integrating with the Zid API (orders, products, customers, etc.)

106 lines (105 loc) 3.85 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ZidCustomerTrigger = void 0; const n8n_workflow_1 = require("n8n-workflow"); const GenericZidApi_1 = require("./GenericZidApi"); class ZidCustomerTrigger { constructor() { this.description = { displayName: 'Zid Customer Trigger', name: 'zidCustomerTrigger', group: ['trigger'], version: 1, description: 'Triggers workflow on new Zid customers', defaults: { name: 'New Zid Customer', }, inputs: [], outputs: ['main'], credentials: [ { name: 'zidOAuth2Api', required: true, }, ], properties: [ { displayName: 'Polling Interval (minutes)', name: 'pollInterval', type: 'number', default: 10, description: 'How often to check for new customers (in minutes)', typeOptions: { minValue: 1, maxValue: 60, }, }, { displayName: 'Limit', name: 'limit', type: 'number', default: 50, description: 'Maximum number of customers to fetch per poll', typeOptions: { minValue: 1, maxValue: 100, }, }, ], }; } async trigger() { const pollInterval = this.getNodeParameter('pollInterval'); const limit = this.getNodeParameter('limit'); const credentials = await this.getCredentials('zidOAuth2Api'); if (!credentials) { throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'No credentials found!'); } const zidApi = new GenericZidApi_1.GenericZidApi('https://api.zid.sa/v1', credentials.accessToken); let lastCustomerId = null; let isFirstRun = true; const pollForCustomers = async () => { try { const params = { limit, sort: 'created_at', order: 'desc', }; if (lastCustomerId && !isFirstRun) { params.since_id = lastCustomerId; } const response = await zidApi.request({ method: 'GET', url: '/customers', params, }); const customers = response.data || []; if (customers.length > 0) { lastCustomerId = customers[0].id; if (isFirstRun) { isFirstRun = false; return; } for (const customer of customers.reverse()) { this.emit([this.helpers.returnJsonArray([customer])]); } } isFirstRun = false; } catch (error) { this.emit([this.helpers.returnJsonArray([{ error: `Failed to fetch customers: ${error.message}`, timestamp: new Date().toISOString(), }])]); } }; await pollForCustomers(); const intervalId = setInterval(pollForCustomers, pollInterval * 60 * 1000); return { closeFunction: async () => { clearInterval(intervalId); }, }; } } exports.ZidCustomerTrigger = ZidCustomerTrigger;