feat(airtrail): use the AirTrail /api/v1 routes, and keep the legacy routes

AirTrail 3.13 adds /api/v1 and marks the /api/flight/* routes as
deprecated. TREK now asks the public discovery document GET /api/v1
and uses v1 when the instance has it. It uses the legacy routes for
an older instance. The client methods keep their signatures, and the
sync hash stays the same, so a linked flight does not sync again
when an instance changes to v1.

The probe cache holds only a clear answer: 200 with the discovery
document gives v1, and 404 gives legacy. The cache is per AirTrail
URL, for 10 minutes. A timeout, a 5xx or a network error fails that
call only. A 401, a 403 or a page that is not the discovery document
uses legacy for that call only. A 404 for one flight makes the client
ask the probe again before it reports the flight as deleted.

A missing scope gives AirtrailScopeError, which names the scope. It
does not unlink a flight. The API key hint and the help step list
the scopes for read and for write-back, in all languages.

Each new request goes through safeFetch, with the SSRF guard, the
timeout and the size cap. The flight list reads pages of 100 and
fails above 50 pages. A failed list unlinks nothing.

airtrail-v1.ts translates between the v1 shapes and the legacy
shapes. A write-back looks up the airport, airline and aircraft ids,
and changes each local time to a UTC instant in the zone of its own
airport. It writes each instant in the +00:00 form of the legacy
save, because AirTrail stores the string as it gets it and the sync
hash reads that string.

The tests cover both APIs over HTTP, the probe cache rules, the sync
hash on a switch and on a save, the page limit, the scope error, and
the UTC conversion across midnight, the date line and daylight-saving
changes.
This commit is contained in:
aaronspruit
2026-11-16 18:52:57 -08:00
committed by Maurice
parent 3e0a2ef8ed
commit 76ff6e15b1
61 changed files with 1442 additions and 74 deletions
@@ -61,7 +61,9 @@ export class AirtrailSyncService {
try {
flights = await this.client.listFlights(creds);
} catch (err) {
// A failed list detaches nothing. Without a full list, no flight is known to be deleted in AirTrail.
if (err instanceof AirtrailAuthError) logError(`AirTrail sync: invalid API key for user ${uid}`);
else logError(`AirTrail sync for user ${uid}: ${err instanceof Error ? err.message : err}`);
return 0;
}
const byId = new Map(flights.map((f) => [String(f.id), f]));
+267
View File
@@ -0,0 +1,267 @@
import { wallClockInstant } from '../common/timezoneService';
import type { AirtrailAirport, AirtrailFlightRaw, AirtrailSavePayload } from './airtrail.client';
/**
* The translation between AirTrail's `/api/v1` and the shapes the rest of TREK
* uses (AirtrailFlightRaw, AirtrailSavePayload), which are the shapes of the
* legacy `/api/flight/*` routes. The callers use one shape for each API that an
* instance speaks. This file is the only place that knows the difference.
*
* The contract comes from AirTrail 3.13.0 to 3.14.0 (`src/lib/api/v1/schemas.ts`,
* `src/lib/api/v1/dto.ts`). The v1 contract is the same in these versions.
*
* The functions are pure, so the unit test gives them fixture objects.
*/
/** An airport as v1 returns it, on a flight and from `GET /api/v1/airports`. */
export interface AirtrailV1Airport {
id: number;
icao: string | null;
iata: string | null;
name: string | null;
latitude: number | null;
longitude: number | null;
timezone: string | null;
country: string | null;
}
/** An airline or aircraft as v1 returns it. Aircraft have no IATA code. */
export interface AirtrailV1Entity {
id: number;
name: string | null;
icao: string | null;
iata?: string | null;
}
interface AirtrailV1Passenger {
id: number;
user: { id: string } | null;
guestName: string | null;
seat: string | null;
seatNumber: string | null;
seatClass: string | null;
flightReason: string | null;
}
/** A flight as `GET /api/v1/flights` and `GET /api/v1/flights/{id}` return it. */
export interface AirtrailV1Flight {
id: number;
from: AirtrailV1Airport | null;
to: AirtrailV1Airport | null;
airline: AirtrailV1Entity | null;
aircraft: AirtrailV1Entity | null;
passengers: AirtrailV1Passenger[];
[key: string]: unknown;
}
/** What a v1 write needs that a code-based payload does not carry. */
export interface AirtrailV1References {
from: AirtrailV1Airport;
to: AirtrailV1Airport;
airlineId: number | null;
aircraftId: number | null;
/** The key owner's AirTrail user id, for a `<USER_ID>` passenger. */
selfUserId: string | null;
}
/** A payload that cannot become a valid v1 body. The message is for the log. */
export class AirtrailV1InputError extends Error {
constructor(message: string) {
super(message);
this.name = 'AirtrailV1InputError';
}
}
/** The placeholder the legacy save resolved to the key owner. */
export const AIRTRAIL_SELF_USER_PLACEHOLDER = '<USER_ID>';
function toAirport(a: AirtrailV1Airport | null): AirtrailAirport | null {
if (!a) return null;
return {
id: a.id,
icao: a.icao,
iata: a.iata,
name: a.name,
lat: a.latitude,
lon: a.longitude,
tz: a.timezone,
country: a.country,
};
}
/**
* A v1 flight in the legacy shape. Airports rename their coordinate and zone
* keys, and a passenger names its user as an object instead of a `userId`.
* Every other key passes through, so `buildSavePayload` still carries the
* AirTrail-owned fields (terminal, gate, takeoff and landing times) it does not
* model.
*/
export function fromAirtrailV1Flight(f: AirtrailV1Flight): AirtrailFlightRaw {
return {
...(f as unknown as AirtrailFlightRaw),
from: toAirport(f.from),
to: toAirport(f.to),
passengers: (f.passengers ?? []).map((p) => ({
userId: p.user?.id ?? null,
guestName: p.guestName,
seat: p.seat,
seatNumber: p.seatNumber,
seatClass: p.seatClass,
flightReason: p.flightReason,
})),
};
}
/**
* The entry of a search result whose code is `code`: an ICAO match first, then
* an IATA match, as the legacy save looked up an airport. With `icaoOnly`, an
* IATA match does not count, as the legacy save looked up an airline and an
* aircraft.
*/
export function pickAirtrailByCode<T extends { icao?: string | null; iata?: string | null }>(
rows: T[],
code: string,
icaoOnly: boolean,
): T | null {
const wanted = code.trim().toUpperCase();
const icao = rows.find((r) => r.icao?.toUpperCase() === wanted);
if (icao || icaoOnly) return icao ?? null;
return rows.find((r) => r.iata?.toUpperCase() === wanted) ?? null;
}
const DATE = /^\d{4}-\d{2}-\d{2}/;
const FULL_ISO = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})$/;
function datePart(value: unknown): string | null {
return typeof value === 'string' && DATE.test(value) ? value.slice(0, 10) : null;
}
function text(value: unknown): string | null {
return typeof value === 'string' ? value : null;
}
/**
* A local date and `HH:MM` at an airport, as an ISO instant. Null when there is no time.
*
* AirTrail stores the string as it gets it, and the sync hash reads that string.
* The instant ends in `+00:00`, as the legacy save wrote it, so that a save
* that changes no time keeps the hash.
*/
function localInstant(date: string | null, time: unknown, zone: string | null, field: string): string | null {
if (!date || typeof time !== 'string' || !time) return null;
const ms = wallClockInstant(date, time, zone || 'UTC');
if (ms === null) throw new AirtrailV1InputError(`Invalid ${field} time "${time}" on ${date}`);
return new Date(ms).toISOString().replace(/Z$/, '+00:00');
}
/**
* A takeoff or landing time. The payload carries it as AirTrail returned it (an
* ISO instant) unless a caller set the date and `HH:MM` form; the instant then
* passes through unchanged.
*/
function carriedInstant(p: Record<string, unknown>, key: string, zone: string | null): string | null {
if (`${key}Time` in p) return localInstant(datePart(p[key]), p[`${key}Time`], zone, key);
const value = p[key];
return typeof value === 'string' && FULL_ISO.test(value) ? value : null;
}
/**
* A legacy save payload as a v1 flight body (`POST /api/v1/flights`,
* `PUT /api/v1/flights/{id}`), with the rules the legacy save applied:
* - Departure and its scheduled time are the local wall clock at the origin,
* arrival and its scheduled time at the destination. A date without a time
* gives no instant. An arrival time without an arrival date takes the
* departure date.
* - `date` is the departure date, else the scheduled departure date.
* - A precision other than `day` keeps only the departure, at 10:00 UTC.
* - A flight-level reason fills each passenger that has none.
*
* v1 does not derive `duration`, so it is the departure-to-arrival time when
* both are known, else the duration AirTrail had.
*
* v1 replaces every field a PUT omits with its default, so the body names each
* field except `track`. Without a track, AirTrail keeps the stored track. A
* track in the body needs the `tracks.write` scope.
*/
export function toAirtrailV1FlightInput(
payload: AirtrailSavePayload,
refs: AirtrailV1References,
): Record<string, unknown> {
const p = payload as unknown as Record<string, unknown>;
const fromTz = refs.from.timezone;
const toTz = refs.to.timezone;
const depDate = datePart(p.departure);
const date = depDate ?? datePart(p.departureScheduled);
if (!date) throw new AirtrailV1InputError('A departure date is required');
const datePrecision = text(p.datePrecision) ?? 'day';
const passengers = (payload.passengers ?? payload.seats ?? []).map((s) => {
const userId = s.userId === AIRTRAIL_SELF_USER_PLACEHOLDER ? refs.selfUserId : s.userId;
if (s.userId === AIRTRAIL_SELF_USER_PLACEHOLDER && !userId)
throw new AirtrailV1InputError('The AirTrail user of this API key is unknown');
return {
userId: userId ?? null,
guestName: s.guestName ?? null,
seat: s.seat ?? null,
seatNumber: s.seatNumber ?? null,
seatClass: s.seatClass ?? null,
flightReason: s.flightReason ?? payload.flightReason ?? null,
};
});
let times: Record<string, string | null>;
if (datePrecision !== 'day') {
times = {
departure: `${date}T10:00:00.000+00:00`,
arrival: null,
departureScheduled: null,
arrivalScheduled: null,
takeoffScheduled: null,
takeoffActual: null,
landingScheduled: null,
landingActual: null,
};
} else {
const arrivalDate = datePart(p.arrival) ?? (p.arrivalTime ? depDate : null);
times = {
departure: localInstant(depDate, p.departureTime, fromTz, 'departure'),
arrival: localInstant(arrivalDate, p.arrivalTime, toTz, 'arrival'),
departureScheduled: localInstant(
datePart(p.departureScheduled),
p.departureScheduledTime,
fromTz,
'scheduled departure',
),
arrivalScheduled: localInstant(datePart(p.arrivalScheduled), p.arrivalScheduledTime, toTz, 'scheduled arrival'),
takeoffScheduled: carriedInstant(p, 'takeoffScheduled', fromTz),
takeoffActual: carriedInstant(p, 'takeoffActual', fromTz),
landingScheduled: carriedInstant(p, 'landingScheduled', toTz),
landingActual: carriedInstant(p, 'landingActual', toTz),
};
}
const known =
times.departure && times.arrival ? (Date.parse(times.arrival) - Date.parse(times.departure)) / 1000 : null;
const duration =
known !== null && known >= 0 ? Math.round(known) : typeof p.duration === 'number' ? p.duration : null;
return {
date,
datePrecision,
...times,
duration,
departureTerminal: text(p.departureTerminal),
departureGate: text(p.departureGate),
arrivalTerminal: text(p.arrivalTerminal),
arrivalGate: text(p.arrivalGate),
flightNumber: text(p.flightNumber),
aircraftReg: text(p.aircraftReg),
note: text(p.note),
fromId: refs.from.id,
toId: refs.to.id,
airlineId: refs.airlineId,
aircraftId: refs.aircraftId,
passengers,
};
}
+265 -17
View File
@@ -1,30 +1,66 @@
import { safeFetch } from '../../utils/ssrfGuard';
import {
AirtrailV1InputError,
fromAirtrailV1Flight,
pickAirtrailByCode,
AIRTRAIL_SELF_USER_PLACEHOLDER,
toAirtrailV1FlightInput,
type AirtrailV1Airport,
type AirtrailV1Entity,
type AirtrailV1Flight,
} from './airtrail-v1';
import { Injectable } from '@nestjs/common';
/**
* Thin HTTP client for the AirTrail REST API (github.com/johanohly/AirTrail).
* This is the ONLY place that talks to a user's AirTrail instance.
*
* Verified against AirTrail source:
* - Auth: `Authorization: Bearer <key>`; a key maps to exactly one user.
* - GET /api/flight/list — defaults to scope=mine. We NEVER send a scope
* param so the key only ever returns its owner's own flights (isolation
* holds even if an admin key is pasted).
* - GET /api/flight/get/{id}
* - POST /api/flight/save — `id` present => update, else create. The
* passenger list is required (>=1). An entry with userId '<USER_ID>' is
* attributed to the key owner server-side, so we never need the caller's
* AirTrail user id.
* - AirTrail 3.12.0 renamed that list from `seats` to `passengers` and moved
* flightReason from the flight onto each passenger, with no alias on either
* side (verified against running 3.11.1 and 3.12.0 instances: each returns
* its own key and null for the other). TREK reads and writes both shapes so
* one build works against either version.
* AirTrail 3.13.0 and later serve the versioned API under `/api/v1`. They mark
* the `/api/flight/*` routes as deprecated, and the next major release removes
* them. Older instances have only `/api/flight/*`. The client asks the public
* discovery document `GET /api/v1` which API an instance has, and keeps the
* answer for FLAVOR_TTL_MS (see `apiFlavor`). A 404 from a flight route cannot
* tell the difference, because v1 also answers 404 for a flight that does not exist.
*
* Both APIs, verified against AirTrail source:
* - Auth: `Authorization: Bearer <key>`; a key maps to exactly one user. A key
* made before 3.13.0 holds every scope. A newer key needs `flight.read.own`,
* and for the write-back also `flight.update.own`,
* `flight.passengers.manage.own` (a PUT that changes a passenger, for example
* the seat), `reference_data.read` (code lookups) and `profile.read`
* (`GET /api/v1/me`, for a flight with no passenger). A save with no id also
* needs `flight.create.own`. A missing scope raises AirtrailScopeError, which
* names it.
* - The flight list defaults to scope=mine. We NEVER send a scope param so the
* key only ever returns its owner's own flights (isolation holds even if an
* admin key is pasted). v1 gives the list in pages, and the client reads every page.
* - Legacy: GET /api/flight/list, GET /api/flight/get/{id}, and
* POST /api/flight/save (`id` present => update, else create), with airports,
* airline and aircraft as codes and times as a local date plus `HH:MM`. An
* entry with userId '<USER_ID>' is attributed to the key owner server-side.
* - v1: GET /api/v1/flights, GET /api/v1/flights/{id}, POST /api/v1/flights,
* PUT /api/v1/flights/{id}, with numeric ids and ISO instants. airtrail-v1.ts
* translates both ways, so callers use the legacy shapes for either API.
* - The passenger list is required (>=1). AirTrail 3.12.0 renamed it from
* `seats` to `passengers` and moved flightReason from the flight onto each
* passenger, with no alias on either side (verified against running 3.11.1
* and 3.12.0 instances: each returns its own key and null for the other).
* TREK reads and writes both shapes so one build works against either version.
* - There is no webhook and no updated_at on a flight, so change detection is
* snapshot-hash based (see airtrailSync).
*/
const TIMEOUT_MS = 12000;
/** How long the client keeps the answer of the discovery probe. After this time, it sees an AirTrail upgrade. */
const FLAVOR_TTL_MS = 10 * 60_000;
/** The largest page `GET /api/v1/flights` gives. */
const V1_PAGE_LIMIT = 100;
/**
* The most list pages read in one call (5000 flights). Past it the list fails
* instead of answering a part, because the sync detaches every linked flight
* that is missing from the list.
*/
const V1_MAX_PAGES = 50;
export interface AirtrailCreds {
/** Instance origin without a trailing /api. */
@@ -40,6 +76,24 @@ export class AirtrailAuthError extends Error {
}
}
/**
* A v1 key that is valid but does not have a scope that the request needs. It is
* not an AirtrailAuthError, because the key still works for its other scopes.
* A caller must not detach linked flights for this error.
*/
export class AirtrailScopeError extends Error {
readonly scope: string | null;
constructor(scope: string | null) {
super(
scope
? `The AirTrail API key lacks the scope ${scope}. Add it to the key in AirTrail, or create a new key.`
: 'The AirTrail API key lacks a scope that this request needs.',
);
this.name = 'AirtrailScopeError';
this.scope = scope;
}
}
export class AirtrailRequestError extends Error {
status?: number;
constructor(message: string, status?: number) {
@@ -179,6 +233,25 @@ async function parseJson<T>(resp: Response): Promise<T> {
}
}
/** The error of a v1 error body (`{error:{code,message,details}}`), when the response holds one. */
async function airtrailV1Error(resp: Response): Promise<{ code: string | null; message: string } | null> {
try {
const body = JSON.parse(await resp.text()) as { error?: { code?: unknown; message?: unknown; details?: unknown } };
const message = typeof body?.error?.message === 'string' ? body.error.message : null;
if (!message) return null;
const code = typeof body.error?.code === 'string' ? body.error.code : null;
const details = body.error?.details;
return { code, message: details === undefined ? message : `${message}: ${JSON.stringify(details)}` };
} catch {
return null;
}
}
/** The scope name in AirTrail's `insufficient_scope` message ("The credential requires flight.read.own"). */
function scopeIn(message: string): string | null {
return /\b[a-z_]+(?:\.[a-z_]+)+\b/.exec(message)?.[0] ?? null;
}
async function request(creds: AirtrailCreds, path: string, init: RequestInit): Promise<Response> {
const url = apiBase(creds.baseUrl) + path;
let resp: Response;
@@ -200,11 +273,21 @@ async function request(creds: AirtrailCreds, path: string, init: RequestInit): P
throw new AirtrailRequestError(err instanceof Error ? err.message : 'Could not reach AirTrail');
}
if (resp.status === 401 || resp.status === 403) {
throw new AirtrailAuthError();
// v1 gives the cause, for example the scope that the key does not have. The legacy API does not.
const reason = await airtrailV1Error(resp);
if (reason?.code === 'insufficient_scope') throw new AirtrailScopeError(scopeIn(reason.message));
throw reason ? new AirtrailAuthError(`AirTrail refused the request: ${reason.message}`) : new AirtrailAuthError();
}
return resp;
}
async function airtrailV1Failure(resp: Response, action: string): Promise<AirtrailRequestError> {
const reason = await airtrailV1Error(resp);
return new AirtrailRequestError(reason?.message ?? `AirTrail ${action} failed (HTTP ${resp.status})`, resp.status);
}
type ApiFlavor = 'v1' | 'legacy';
/**
* The AirTrail HTTP surface, as a provider.
*
@@ -215,7 +298,11 @@ async function request(creds: AirtrailCreds, path: string, init: RequestInit): P
*/
@Injectable()
export class AirtrailClient {
/** The API each instance speaks, by API base URL, with the time it was asked. */
private readonly flavors = new Map<string, { flavor: ApiFlavor; at: number }>();
async listFlights(creds: AirtrailCreds): Promise<AirtrailFlightRaw[]> {
if ((await this.apiFlavor(creds)) === 'v1') return this.listFlightsV1(creds);
const resp = await request(creds, '/flight/list', { method: 'GET' });
if (!resp.ok) throw new AirtrailRequestError(`AirTrail list failed (HTTP ${resp.status})`, resp.status);
const data = await parseJson<{ flights?: AirtrailFlightRaw[] }>(resp);
@@ -223,14 +310,31 @@ export class AirtrailClient {
}
async getFlight(creds: AirtrailCreds, id: number): Promise<AirtrailFlightRaw | null> {
const resp = await request(creds, `/flight/get/${id}`, { method: 'GET' });
const flavor = await this.apiFlavor(creds);
const flight = await this.getFlightAs(creds, id, flavor);
if (flight) return flight;
// A 404 from a stale answer (AirTrail was upgraded or downgraded) looks like a deleted
// flight, and a caller detaches a deleted flight. Ask the probe again before null.
this.flavors.delete(apiBase(creds.baseUrl));
const fresh = await this.apiFlavor(creds);
return fresh === flavor ? null : this.getFlightAs(creds, id, fresh);
}
private async getFlightAs(creds: AirtrailCreds, id: number, flavor: ApiFlavor): Promise<AirtrailFlightRaw | null> {
const v1 = flavor === 'v1';
const resp = await request(creds, v1 ? `/v1/flights/${id}` : `/flight/get/${id}`, { method: 'GET' });
if (resp.status === 404) return null;
if (!resp.ok) throw new AirtrailRequestError(`AirTrail get failed (HTTP ${resp.status})`, resp.status);
if (v1) {
const data = await parseJson<{ data?: AirtrailV1Flight }>(resp);
return data.data ? fromAirtrailV1Flight(data.data) : null;
}
const data = await parseJson<{ flight?: AirtrailFlightRaw }>(resp);
return data.flight ?? null;
}
async saveFlight(creds: AirtrailCreds, payload: AirtrailSavePayload): Promise<{ id?: number }> {
if ((await this.apiFlavor(creds)) === 'v1') return this.saveFlightV1(creds, payload);
const resp = await request(creds, '/flight/save', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
@@ -250,4 +354,148 @@ export class AirtrailClient {
const data = await parseJson<{ id?: number }>(resp);
return { id: data.id };
}
/**
* Which API the instance speaks. `GET /api/v1` is public and answers a
* discovery document with `api.version` on 3.13.0 and later. An older
* instance answers 404. The client keeps only these two answers. For each
* other answer, the client asks again on the next call:
* - A 5xx, a timeout or a network error fails this call.
* - A page that is not the discovery document (for example a login page in
* front of AirTrail) sends this call to the legacy route. The error of
* that route explains a wrong URL.
*/
private async apiFlavor(creds: AirtrailCreds): Promise<ApiFlavor> {
const base = apiBase(creds.baseUrl);
const known = this.flavors.get(base);
if (known && Date.now() - known.at < FLAVOR_TTL_MS) return known.flavor;
let resp: Response;
try {
resp = await request(creds, '/v1', { method: 'GET' });
} catch (err) {
// `GET /api/v1` is public in AirTrail, so a 401 or 403 comes from a proxy in front of it.
// It says nothing about the key. Use the legacy route for this call, and do not keep the answer.
if (err instanceof AirtrailAuthError || err instanceof AirtrailScopeError) return 'legacy';
throw err;
}
let flavor: ApiFlavor;
let keep = true;
if (resp.status === 404) {
flavor = 'legacy';
} else if (resp.ok) {
let version: unknown;
try {
version = (JSON.parse(await resp.text()) as { api?: { version?: unknown } })?.api?.version;
} catch {
version = undefined;
}
flavor = version === 'v1' ? 'v1' : 'legacy';
keep = flavor === 'v1';
} else {
throw new AirtrailRequestError(`AirTrail did not answer (HTTP ${resp.status})`, resp.status);
}
if (keep) {
if (this.flavors.size >= 1000) this.flavors.clear();
this.flavors.set(base, { flavor, at: Date.now() });
}
return flavor;
}
/**
* Every page of `GET /api/v1/flights`, one after the other, because each
* request needs the cursor of the page before it.
*/
private async listFlightsV1(
creds: AirtrailCreds,
cursor: string | null = null,
flights: AirtrailFlightRaw[] = [],
seen: Set<string> = new Set(),
): Promise<AirtrailFlightRaw[]> {
const query = new URLSearchParams({ limit: String(V1_PAGE_LIMIT) });
if (cursor) query.set('cursor', cursor);
const resp = await request(creds, `/v1/flights?${query}`, { method: 'GET' });
if (!resp.ok) throw new AirtrailRequestError(`AirTrail list failed (HTTP ${resp.status})`, resp.status);
const body = await parseJson<{ data?: AirtrailV1Flight[]; page?: { nextCursor?: string | null } }>(resp);
for (const f of body.data ?? []) flights.push(fromAirtrailV1Flight(f));
const next = body.page?.nextCursor ?? null;
if (!next) return flights;
// A cursor that came before makes an endless loop. AirTrail does not send one, but a caching proxy can.
if (seen.has(next)) throw new AirtrailRequestError('AirTrail repeated a page cursor');
seen.add(next);
if (seen.size >= V1_MAX_PAGES)
throw new AirtrailRequestError(`AirTrail has more than ${V1_MAX_PAGES * V1_PAGE_LIMIT} flights`);
return this.listFlightsV1(creds, next, flights, seen);
}
private async saveFlightV1(creds: AirtrailCreds, payload: AirtrailSavePayload): Promise<{ id?: number }> {
const [from, to, airline, aircraft] = await Promise.all([
this.findByCode<AirtrailV1Airport>(creds, 'airports', payload.from, false, 'departure airport'),
this.findByCode<AirtrailV1Airport>(creds, 'airports', payload.to, false, 'arrival airport'),
payload.airline ? this.findByCode<AirtrailV1Entity>(creds, 'airlines', payload.airline, true, 'airline') : null,
payload.aircraft
? this.findByCode<AirtrailV1Entity>(creds, 'aircraft', payload.aircraft, true, 'aircraft')
: null,
]);
const people = payload.passengers ?? payload.seats ?? [];
const selfUserId = people.some((s) => s.userId === AIRTRAIL_SELF_USER_PLACEHOLDER)
? await this.selfUserId(creds)
: null;
let body: Record<string, unknown>;
try {
body = toAirtrailV1FlightInput(payload, {
from,
to,
airlineId: airline?.id ?? null,
aircraftId: aircraft?.id ?? null,
selfUserId,
});
} catch (err) {
if (err instanceof AirtrailV1InputError) throw new AirtrailRequestError(err.message, 400);
throw err;
}
const update = payload.id !== undefined && payload.id !== null;
const resp = await request(creds, update ? `/v1/flights/${payload.id}` : '/v1/flights', {
method: update ? 'PUT' : 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
if (!resp.ok) throw await airtrailV1Failure(resp, 'save');
// The legacy save answers an id only for a new flight. This method does the same.
if (update) return {};
const data = await parseJson<{ data?: { id?: number } }>(resp);
return { id: data.data?.id };
}
/**
* The row whose code is `code`, from a v1 reference search. The search also
* matches names, so `pickAirtrailByCode` compares the code again.
*/
private async findByCode<T extends { id: number; icao?: string | null; iata?: string | null }>(
creds: AirtrailCreds,
kind: 'airports' | 'airlines' | 'aircraft',
code: string,
icaoOnly: boolean,
label: string,
): Promise<T> {
const resp = await request(creds, `/v1/${kind}?${new URLSearchParams({ query: code.trim() })}`, {
method: 'GET',
});
if (!resp.ok) throw await airtrailV1Failure(resp, `${label} lookup`);
const body = await parseJson<{ data?: T[] }>(resp);
const row = pickAirtrailByCode(body.data ?? [], code, icaoOnly);
if (!row) throw new AirtrailRequestError(`Invalid ${label}: ${code}`, 400);
return row;
}
/** The AirTrail user id of the key owner, which v1 needs where the legacy save took '<USER_ID>'. */
private async selfUserId(creds: AirtrailCreds): Promise<string> {
const resp = await request(creds, '/v1/me', { method: 'GET' });
if (!resp.ok) throw await airtrailV1Failure(resp, 'profile read');
const body = await parseJson<{ data?: { id?: unknown } }>(resp);
if (typeof body.data?.id !== 'string') throw new AirtrailRequestError('AirTrail did not name the key owner');
return body.data.id;
}
}