|
| 1 | +import { BaseCommand } from '../command.js' |
| 2 | +import { Flags } from '@oclif/core' |
| 3 | +import { findStation, nearestStation } from 'neaps' |
| 4 | + |
| 5 | +export default class Extremes extends BaseCommand { |
| 6 | + static override description = 'Get tide extremes for a station' |
| 7 | + |
| 8 | + static override flags = { |
| 9 | + station: Flags.string({ |
| 10 | + description: 'Use the specified station ID', |
| 11 | + helpValue: '<station-id>', |
| 12 | + exclusive: ['near', 'ip'] |
| 13 | + }), |
| 14 | + ip: Flags.boolean({ |
| 15 | + default: false, |
| 16 | + description: 'Use IP geolocation to find nearest station', |
| 17 | + exclusive: ['station', 'near'] |
| 18 | + }), |
| 19 | + near: Flags.string({ |
| 20 | + description: 'Use specified lat,lon to find nearest station', |
| 21 | + helpValue: 'lat,lon', |
| 22 | + exclusive: ['station', 'ip'] |
| 23 | + }), |
| 24 | + date: Flags.string({ |
| 25 | + description: 'ISO date', |
| 26 | + default: new Date().toISOString().slice(0, 10), |
| 27 | + helpValue: 'YYYY-MM-DD' |
| 28 | + }), |
| 29 | + units: Flags.string({ |
| 30 | + description: 'Units for output (meters or feet)', |
| 31 | + default: 'meters', |
| 32 | + helpValue: '<meters|feet>' |
| 33 | + }), |
| 34 | + hours: Flags.string({ |
| 35 | + description: 'Number of hours to predict', |
| 36 | + default: '24' |
| 37 | + }) |
| 38 | + } |
| 39 | + |
| 40 | + public async run(): Promise<void> { |
| 41 | + const { flags } = await this.parse(Extremes) |
| 42 | + |
| 43 | + const { date, hours } = flags |
| 44 | + const durationHours = Number(hours) |
| 45 | + |
| 46 | + const station = await getStation(flags) |
| 47 | + const prediction = station.getExtremesPrediction({ |
| 48 | + start: new Date(date), |
| 49 | + end: new Date(new Date(date).getTime() + durationHours * 60 * 60 * 1000), |
| 50 | + units: flags.units as 'meters' | 'feet' |
| 51 | + }) |
| 52 | + |
| 53 | + flags.format.extremes(prediction) |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +async function getStation({ |
| 58 | + station, |
| 59 | + near, |
| 60 | + ip |
| 61 | +}: { |
| 62 | + station?: string |
| 63 | + near?: string |
| 64 | + ip?: boolean |
| 65 | +}) { |
| 66 | + if (station) { |
| 67 | + return findStation(station) |
| 68 | + } |
| 69 | + |
| 70 | + if (near) { |
| 71 | + const [lat, lon] = near.split(',').map(Number) |
| 72 | + return nearestStation({ latitude: lat, longitude: lon }) |
| 73 | + } |
| 74 | + |
| 75 | + if (ip) { |
| 76 | + const res = await fetch('https://reallyfreegeoip.org/json/') |
| 77 | + if (!res.ok) |
| 78 | + throw new Error(`Failed to fetch IP geolocation: ${res.statusText}`) |
| 79 | + return nearestStation(await res.json()) |
| 80 | + } else { |
| 81 | + throw new Error('No station specified. Use --station or --ip flag.') |
| 82 | + } |
| 83 | +} |
0 commit comments