n8n-nodes-sunrise-sunset
Version:
n8n node to work with the Sunrise-Sunset API
196 lines • 8.6 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SunriseSunsetTrigger = void 0;
const n8n_workflow_1 = require("n8n-workflow");
const moment_timezone_1 = __importDefault(require("moment-timezone"));
class SunriseSunsetTrigger {
constructor() {
this.description = {
displayName: 'Sunrise Sunset Trigger',
name: 'sunriseSunsetTrigger',
icon: 'file:sunrise.svg',
group: ['trigger'],
version: 1,
subtitle: '={{$parameter["eventType"]}} - {{$parameter["timeEvent"]}}',
description: 'Triggers when sunrise or sunset occurs at specified location',
defaults: {
name: 'Sunrise Sunset Trigger',
},
inputs: [],
outputs: ["main" /* NodeConnectionType.Main */],
credentials: [],
properties: [
{
displayName: 'Latitude',
name: 'latitude',
type: 'string',
default: '',
placeholder: '36.7201600',
required: true,
description: 'Latitude of the location in decimal degrees',
},
{
displayName: 'Longitude',
name: 'longitude',
type: 'string',
default: '',
placeholder: '-4.4203400',
required: true,
description: 'Longitude of the location in decimal degrees',
},
{
displayName: 'Event Type',
name: 'eventType',
type: 'options',
options: [
{
name: 'Sunrise',
value: 'sunrise',
description: 'Trigger at sunrise',
},
{
name: 'Sunset',
value: 'sunset',
description: 'Trigger at sunset',
},
],
default: 'sunrise',
description: 'The type of event to trigger on',
},
{
displayName: 'Time Event',
name: 'timeEvent',
type: 'options',
options: [
{
name: 'Actual Time',
value: 'actual',
description: 'Actual sunrise or sunset time',
},
{
name: 'Civil Twilight Begin',
value: 'civil_twilight_begin',
description: 'Civil twilight starts',
},
{
name: 'Civil Twilight End',
value: 'civil_twilight_end',
description: 'Civil twilight ends',
},
{
name: 'Nautical Twilight Begin',
value: 'nautical_twilight_begin',
description: 'Nautical twilight starts',
},
{
name: 'Nautical Twilight End',
value: 'nautical_twilight_end',
description: 'Nautical twilight ends',
},
{
name: 'Astronomical Twilight Begin',
value: 'astronomical_twilight_begin',
description: 'Astronomical twilight starts',
},
{
name: 'Astronomical Twilight End',
value: 'astronomical_twilight_end',
description: 'Astronomical twilight ends',
},
],
default: 'actual',
description: 'The specific twilight time to use',
},
{
displayName: 'Timezone',
name: 'timezone',
type: 'string',
default: '',
placeholder: 'Europe/Madrid',
description: 'The timezone to use (e.g., Europe/Madrid). Defaults to system timezone if left empty',
},
],
};
}
async trigger() {
const latitude = this.getNodeParameter('latitude', '');
const longitude = this.getNodeParameter('longitude', '');
const eventType = this.getNodeParameter('eventType', '');
const timeEvent = this.getNodeParameter('timeEvent', '');
const timezone = this.getNodeParameter('timezone', '');
if (!latitude || !longitude) {
throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'Latitude and longitude must be provided');
}
const latNum = parseFloat(latitude);
const longNum = parseFloat(longitude);
if (isNaN(latNum) || isNaN(longNum)) {
throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'Latitude and longitude must be valid numbers');
}
if (latNum < -90 || latNum > 90) {
throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'Latitude must be between -90 and 90');
}
if (longNum < -180 || longNum > 180) {
throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'Longitude must be between -180 and 180');
}
const systemTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
const useTimezone = timezone || systemTimezone;
const fetchWeeklyData = async () => {
const now = (0, moment_timezone_1.default)().tz(useTimezone);
const weekData = [];
for (let i = 0; i < 7; i++) {
const date = (0, moment_timezone_1.default)(now).add(i, 'days');
const formattedDate = date.format('YYYY-MM-DD');
try {
const endpoint = `https://api.sunrise-sunset.org/json?lat=${latitude}&lng=${longitude}&date=${formattedDate}&formatted=0`;
const response = await this.helpers.request({
method: 'GET',
url: endpoint,
json: true,
});
if (response.status !== 'OK') {
throw new Error(`Failed to fetch data: ${JSON.stringify(response)}`);
}
let eventTime;
if (timeEvent === 'actual') {
eventTime = response.results[eventType];
}
else {
eventTime = response.results[timeEvent];
}
if (!eventTime) {
throw new Error(`Event time not found for ${formattedDate}`);
}
const utcTime = moment_timezone_1.default.utc(eventTime);
const localTime = utcTime.clone().tz(useTimezone);
weekData.push({
date: formattedDate,
utcTime: utcTime.format(),
localTime: localTime.format(),
event: eventType,
timeEvent: timeEvent,
timezone: useTimezone,
raw: response,
});
}
catch (error) {
console.error(`Error fetching data for ${formattedDate}:`, error);
}
}
return weekData;
};
const emitData = async () => {
const weeklyData = await fetchWeeklyData();
for (const item of weeklyData) {
this.emit([this.helpers.returnJsonArray([item])]);
}
};
return {
manualTriggerFunction: emitData,
};
}
}
exports.SunriseSunsetTrigger = SunriseSunsetTrigger;
//# sourceMappingURL=SunriseSunsetTrigger.node.js.map