n8n-nodes-zid-beta
Version:
BETA; n8n custom nodes for integrating with the Zid API (orders, products, customers, etc.)
114 lines (113 loc) • 4.33 kB
JavaScript
;
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!');
}
// Extract both tokens from OAuth2 credentials
const zidCredentials = {
accessToken: credentials.accessToken || credentials.access_token,
authorizationToken: credentials.authorizationToken || credentials.authorization,
};
if (!zidCredentials.accessToken || !zidCredentials.authorizationToken) {
throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'Missing required tokens. Please ensure OAuth2 authentication is properly configured.');
}
const zidApi = new GenericZidApi_1.GenericZidApi(zidCredentials);
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;