mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-03 09:38:54 +00:00
feat(api): add a versioned read-only public API for integrations
TREK's REST surface is internal: it answers a session cookie, carries no version, and changes with the client. That is fine for our own frontend and useless for anyone building against us — the Dawarich integration people have been asking for since April needs something it can rely on not moving. So this adds a small one rather than opening the existing 549 endpoints: GET /api/v1/trips the trips the caller can reach GET /api/v1/trips/:id one trip, ?include= picks the sections Auth reuses the trek_ tokens users already manage under Settings, via Bearer or X-API-Key. No new credential type, no new table — the guard calls the same hash lookup the MCP transport does. It deliberately refuses a session JWT and, for now, OAuth bearers: a credential whose scopes this surface does not yet interpret is worse than one it rejects outright. Access is decided per trip against canAccessTrip, the same owner-or-member predicate as everywhere else, and a trip the caller may not read answers 404 identically to one that does not exist — a 403 would confirm the id is real and turn the endpoint into a way to count someone else's trips. The payload is not the rows. Ids, foreign keys and order_index stay inside; accommodation day ids resolve to ISO dates, places arrive in planned order, and every dated thing carries its date so a consumer can join on days rather than on ids it has no way to look up.
This commit is contained in:
@@ -11,6 +11,7 @@ import { GlobalAuthGuard } from './auth/global-auth.guard';
|
||||
import { MfaPolicyGuard } from './auth/mfa-policy.guard';
|
||||
import { ManagedGuard } from './common/managed.guard';
|
||||
import { WeatherModule } from './weather/weather.module';
|
||||
import { PublicApiModule } from './public-api/public-api.module';
|
||||
import { HelpModule } from './help/help.module';
|
||||
import { AirportsModule } from './airports/airports.module';
|
||||
import { ConfigModule } from './config/config.module';
|
||||
@@ -75,7 +76,7 @@ import { RealtimeGatewayModule } from './realtime/realtime-gateway.module';
|
||||
* migrated.
|
||||
*/
|
||||
@Module({
|
||||
imports: [AppConfigModule, DatabaseModule, RealtimeModule, RealtimeGatewayModule, SchedulingModule, McpModule.forRoot({ accessPolicy: trekMcpAccessPolicy, validateAccess: trekMcpValidateAccess }), HealthModule, PlatformModule, McpTransportModule, WeatherModule, HelpModule, AirportsModule, ConfigModule, SystemNoticesModule, GeoModule, MapsModule, PlaceEnrichmentModule, CategoriesModule, TagsModule, NotificationsModule, AtlasModule, VacayModule, PackingModule, TodoModule, BudgetModule, ReservationsModule, DaysModule, DayNotesModule, AccommodationsModule, AssignmentsModule, PlacesModule, TripsModule, CollabModule, FilesModule, PhotosModule, MemoriesModule, AirtrailModule, JourneyModule, CollectionsModule, ShareModule, TripInviteModule, TransitModule, FeedsModule, SettingsModule, StorageModule, BackupModule, AuthModule, OidcModule, OauthModule, AdminModule, AddonsModule, AuditModule, PermissionsModule, PluginsModule, BookingImportModule, ReservationImportModule, LlmParseModule, ManagedExtModule],
|
||||
imports: [AppConfigModule, DatabaseModule, RealtimeModule, RealtimeGatewayModule, SchedulingModule, McpModule.forRoot({ accessPolicy: trekMcpAccessPolicy, validateAccess: trekMcpValidateAccess }), HealthModule, PlatformModule, McpTransportModule, WeatherModule, PublicApiModule, HelpModule, AirportsModule, ConfigModule, SystemNoticesModule, GeoModule, MapsModule, PlaceEnrichmentModule, CategoriesModule, TagsModule, NotificationsModule, AtlasModule, VacayModule, PackingModule, TodoModule, BudgetModule, ReservationsModule, DaysModule, DayNotesModule, AccommodationsModule, AssignmentsModule, PlacesModule, TripsModule, CollabModule, FilesModule, PhotosModule, MemoriesModule, AirtrailModule, JourneyModule, CollectionsModule, ShareModule, TripInviteModule, TransitModule, FeedsModule, SettingsModule, StorageModule, BackupModule, AuthModule, OidcModule, OauthModule, AdminModule, AddonsModule, AuditModule, PermissionsModule, PluginsModule, BookingImportModule, ReservationImportModule, LlmParseModule, ManagedExtModule],
|
||||
providers: [
|
||||
// Default-deny: a route is authenticated unless it carries @Public() or
|
||||
// @OptionalAuth(), or declares its own @UseGuards chain. Protection used to
|
||||
|
||||
@@ -5,6 +5,7 @@ import { IS_PUBLIC, OPTIONAL_AUTH } from '../auth/public.decorator';
|
||||
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||
import { CookieAuthGuard } from '../auth/cookie-auth.guard';
|
||||
import { OptionalJwtGuard } from '../auth/optional-jwt.guard';
|
||||
import { ApiTokenGuard } from '../public-api/api-token.guard';
|
||||
|
||||
export interface RouteGuardEntry {
|
||||
/** `ControllerClass.methodName` */
|
||||
@@ -21,7 +22,7 @@ export interface RouteGuardEntry {
|
||||
* no req.user, but they never resolve one, so they only ever appear behind one
|
||||
* of these three.
|
||||
*/
|
||||
const AUTHENTICATING_GUARDS: unknown[] = [JwtAuthGuard, CookieAuthGuard, OptionalJwtGuard];
|
||||
const AUTHENTICATING_GUARDS: unknown[] = [JwtAuthGuard, CookieAuthGuard, OptionalJwtGuard, ApiTokenGuard];
|
||||
|
||||
/**
|
||||
* Boot-time gate: every registered route must be authenticated, or say why not.
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import { CanActivate, ExecutionContext, HttpException, Injectable } from '@nestjs/common';
|
||||
import type { Request } from 'express';
|
||||
import { TokenService } from '../tokens/token.service';
|
||||
|
||||
/**
|
||||
* Authenticates a caller of the public API with a long-lived `trek_…` token.
|
||||
*
|
||||
* The tokens are the ones users already manage under Settings → Integrations; this
|
||||
* guard adds no new credential type and no new table. It reuses
|
||||
* `TokenService.verifyMcpToken`, which hashes the presented token with SHA-256 and
|
||||
* looks up the hash — the raw token is never stored and never compared in the
|
||||
* application, so a database read cannot yield a usable credential.
|
||||
*
|
||||
* Deliberately narrower than the MCP transport's `verifyToken`, which also accepts
|
||||
* OAuth bearer tokens and a plain web-session JWT:
|
||||
*
|
||||
* - **No session JWT.** A session cookie leaking into a third-party integration is
|
||||
* exactly what a machine credential exists to prevent, and a JWT that reaches
|
||||
* this surface is almost always an accident.
|
||||
* - **No OAuth tokens (yet).** They carry scopes this surface does not interpret
|
||||
* yet, and accepting a credential whose restrictions you ignore is worse than
|
||||
* refusing it. When `/api/v1` grows write routes, scopes get honoured first.
|
||||
*
|
||||
* The guard authenticates but does not authorise: it resolves `req.user` and stops
|
||||
* there. Which trips that user may read is decided per row against
|
||||
* `DatabaseService.canAccessTrip`, never from anything the caller sent.
|
||||
*/
|
||||
@Injectable()
|
||||
export class ApiTokenGuard implements CanActivate {
|
||||
constructor(private readonly tokens: TokenService) {}
|
||||
|
||||
canActivate(context: ExecutionContext): boolean {
|
||||
const req = context.switchToHttp().getRequest<Request>();
|
||||
const token = extractApiToken(req);
|
||||
if (!token) {
|
||||
throw new HttpException(
|
||||
{ error: 'API token required', code: 'API_TOKEN_REQUIRED' },
|
||||
401,
|
||||
);
|
||||
}
|
||||
const user = this.tokens.verifyMcpToken(token);
|
||||
if (!user) {
|
||||
throw new HttpException(
|
||||
{ error: 'Invalid API token', code: 'API_TOKEN_INVALID' },
|
||||
401,
|
||||
);
|
||||
}
|
||||
req.user = user;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* `Authorization: Bearer trek_…` or `X-API-Key: trek_…`.
|
||||
*
|
||||
* Both spellings exist because integrators expect one or the other and neither is
|
||||
* wrong; the header is the only difference. Anything that is not a `trek_` token is
|
||||
* rejected here rather than passed to the lookup — a session JWT would otherwise
|
||||
* travel one step further into the system than it should, and the hash of an
|
||||
* arbitrary string is a pointless query.
|
||||
*/
|
||||
function extractApiToken(req: Request): string | null {
|
||||
const header = req.headers['authorization'];
|
||||
if (typeof header === 'string' && header.startsWith('Bearer ')) {
|
||||
const candidate = header.slice(7).trim();
|
||||
if (candidate.startsWith('trek_')) return candidate;
|
||||
}
|
||||
const apiKey = req.headers['x-api-key'];
|
||||
if (typeof apiKey === 'string' && apiKey.trim().startsWith('trek_')) {
|
||||
return apiKey.trim();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
import { Controller, Get, HttpException, Param, Query, Req, UseGuards } from '@nestjs/common';
|
||||
import type { Request } from 'express';
|
||||
import {
|
||||
PUBLIC_API_INCLUDES,
|
||||
publicApiIncludeQuerySchema,
|
||||
type PublicApiInclude,
|
||||
type PublicApiTrip,
|
||||
type PublicApiTripList,
|
||||
} from '@trek/shared';
|
||||
import { ApiTokenGuard } from './api-token.guard';
|
||||
import { PublicApiService } from './public-api.service';
|
||||
|
||||
/**
|
||||
* `/api/v1` — the versioned, read-only surface for third-party integrations.
|
||||
*
|
||||
* Everything else under `/api` is internal: it answers a session cookie, carries no
|
||||
* version, and is free to change with the client. This prefix is the opposite
|
||||
* promise, and the version in the path is what makes that promise keepable — a
|
||||
* breaking change ships as `/api/v2` rather than as an edit here.
|
||||
*
|
||||
* The surface is deliberately small. Two read endpoints are enough for the
|
||||
* integrations asking for one (a location tracker enriching its own trips), and a
|
||||
* small contract is one that can actually be honoured. Write access is not a
|
||||
* missing feature: it would need scope enforcement this surface does not implement
|
||||
* yet, and a token that reads everything is a very different thing from one that
|
||||
* can also delete a trip.
|
||||
*/
|
||||
@Controller('api/v1')
|
||||
@UseGuards(ApiTokenGuard)
|
||||
export class PublicApiController {
|
||||
constructor(private readonly api: PublicApiService) {}
|
||||
|
||||
/** Every trip the token's owner can reach, without itineraries. */
|
||||
@Get('trips')
|
||||
listTrips(@Req() req: Request): PublicApiTripList {
|
||||
return { trips: this.api.listTrips(requireUserId(req)) };
|
||||
}
|
||||
|
||||
/**
|
||||
* One trip, with the sections named in `?include=`.
|
||||
*
|
||||
* A trip the caller may not read answers 404, identical to one that does not
|
||||
* exist. That is the point: a 403 would confirm the id is real, which turns the
|
||||
* endpoint into a way to count someone else's trips.
|
||||
*/
|
||||
@Get('trips/:id')
|
||||
getTrip(
|
||||
@Req() req: Request,
|
||||
@Param('id') id: string,
|
||||
@Query('include') include?: string,
|
||||
): PublicApiTrip {
|
||||
const tripId = parseTripId(id);
|
||||
const trip = this.api.getTrip(tripId, requireUserId(req), parseInclude(include));
|
||||
if (!trip) {
|
||||
throw new HttpException({ error: 'Trip not found' }, 404);
|
||||
}
|
||||
return trip;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The guard has already resolved the user; this is the type narrowing plus a
|
||||
* belt-and-braces check. If it ever throws, a route was mounted without the guard —
|
||||
* a 401 is then the right answer, and a loud one.
|
||||
*/
|
||||
function requireUserId(req: Request): number {
|
||||
const id = req.user?.id;
|
||||
if (typeof id !== 'number') {
|
||||
throw new HttpException({ error: 'API token required', code: 'API_TOKEN_REQUIRED' }, 401);
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Trip ids are integers. Anything else is rejected before it reaches a query —
|
||||
* `parseInt` would happily turn "12abc" into 12, and a route that quietly accepts
|
||||
* a mangled id is a route whose logs stop matching reality.
|
||||
*/
|
||||
function parseTripId(raw: string): number {
|
||||
if (!/^\d+$/.test(raw)) {
|
||||
throw new HttpException({ error: 'Invalid trip id' }, 400);
|
||||
}
|
||||
const id = Number(raw);
|
||||
if (!Number.isSafeInteger(id) || id <= 0) {
|
||||
throw new HttpException({ error: 'Invalid trip id' }, 400);
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
/**
|
||||
* `?include=days,notes`. Absent means everything, because a full sync is the common
|
||||
* case and a caller that wants less says so.
|
||||
*
|
||||
* An unknown section is a 400 rather than being ignored: silently dropping a typo
|
||||
* would hand the caller a payload that is missing exactly what they asked for, and
|
||||
* they would debug their own code for it.
|
||||
*/
|
||||
function parseInclude(raw?: string): PublicApiInclude[] {
|
||||
if (raw === undefined || raw.trim() === '') return [...PUBLIC_API_INCLUDES];
|
||||
const parsed = publicApiIncludeQuerySchema.safeParse(raw);
|
||||
if (!parsed.success) {
|
||||
throw new HttpException(
|
||||
{ error: `include must be a comma-separated list of: ${PUBLIC_API_INCLUDES.join(', ')}` },
|
||||
400,
|
||||
);
|
||||
}
|
||||
return parsed.data;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { PublicApiController } from './public-api.controller';
|
||||
import { PublicApiService } from './public-api.service';
|
||||
import { ApiTokenGuard } from './api-token.guard';
|
||||
import { TokensModule } from '../tokens/tokens.module';
|
||||
import { TripMembershipModule } from '../trip-membership/trip-membership.module';
|
||||
|
||||
/**
|
||||
* Public API v1 — the versioned read-only surface for third-party integrations.
|
||||
*
|
||||
* Imports rather than re-implements: token verification comes from TokensModule,
|
||||
* trip access from TripMembershipModule and DatabaseService. This module owns the
|
||||
* payload shaping and nothing else, so there is no second place where "who may read
|
||||
* this trip" is decided.
|
||||
*/
|
||||
@Module({
|
||||
imports: [TokensModule, TripMembershipModule],
|
||||
controllers: [PublicApiController],
|
||||
providers: [PublicApiService, ApiTokenGuard],
|
||||
})
|
||||
export class PublicApiModule {}
|
||||
@@ -0,0 +1,307 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import type {
|
||||
PublicApiAccommodation,
|
||||
PublicApiDay,
|
||||
PublicApiDayNote,
|
||||
PublicApiInclude,
|
||||
PublicApiPlace,
|
||||
PublicApiReservation,
|
||||
PublicApiTrip,
|
||||
PublicApiTripSummary,
|
||||
} from '@trek/shared';
|
||||
import { DatabaseService } from '../database/database.service';
|
||||
import { TripMembershipService } from '../trip-membership/trip-membership.service';
|
||||
|
||||
/**
|
||||
* Assembles the read-only public API payloads.
|
||||
*
|
||||
* Two rules run through everything here:
|
||||
*
|
||||
* 1. **Access is decided per trip, against the database, every time.** The list
|
||||
* comes from `listAccessibleTripIds`, a single trip goes through
|
||||
* `canAccessTrip` — the same predicates the rest of TREK uses (owner or member).
|
||||
* Nothing is filtered in application code after a broad read, because a filter
|
||||
* that is forgotten once leaks everything.
|
||||
* 2. **Rows are never handed out as they are stored.** Ids, foreign keys and
|
||||
* ordering columns stay inside; the caller gets resolved names, dates and times.
|
||||
* That keeps the contract stable when the tables move, and it keeps internal
|
||||
* structure — which user owns what, how ids are numbered — out of the response.
|
||||
*
|
||||
* The child queries are scoped by `trip_id` in SQL rather than by filtering a
|
||||
* wider result set, so a bug in the include handling cannot widen what a caller
|
||||
* sees; at worst it returns less.
|
||||
*/
|
||||
@Injectable()
|
||||
export class PublicApiService {
|
||||
constructor(
|
||||
private readonly db: DatabaseService,
|
||||
private readonly membership: TripMembershipService,
|
||||
) {}
|
||||
|
||||
/** Every trip the token's owner may read, newest first, without itineraries. */
|
||||
listTrips(userId: number): PublicApiTripSummary[] {
|
||||
const ids = this.membership.listAccessibleTripIds(userId);
|
||||
if (ids.length === 0) return [];
|
||||
const rows = this.db.all<TripRow>(
|
||||
`SELECT id, title, description, start_date, end_date, currency, is_archived
|
||||
FROM trips
|
||||
WHERE id IN (${ids.map(() => '?').join(',')})
|
||||
ORDER BY start_date DESC, id DESC`,
|
||||
...ids,
|
||||
);
|
||||
return rows.map(toTripSummary);
|
||||
}
|
||||
|
||||
/**
|
||||
* One trip with the requested sections, or null when the caller may not read it.
|
||||
*
|
||||
* Null covers both "no such trip" and "not yours" on purpose — the controller
|
||||
* turns both into the same 404, so the endpoint cannot be used to probe which
|
||||
* trip ids exist.
|
||||
*/
|
||||
getTrip(tripId: number, userId: number, include: PublicApiInclude[]): PublicApiTrip | null {
|
||||
if (!this.db.canAccessTrip(tripId, userId)) return null;
|
||||
const row = this.db.get<TripRow>(
|
||||
`SELECT id, title, description, start_date, end_date, currency, is_archived
|
||||
FROM trips WHERE id = ?`,
|
||||
tripId,
|
||||
);
|
||||
if (!row) return null;
|
||||
|
||||
const trip: PublicApiTrip = toTripSummary(row);
|
||||
if (include.includes('days')) {
|
||||
trip.days = this.buildDays(tripId, include);
|
||||
}
|
||||
if (include.includes('accommodations')) {
|
||||
trip.accommodations = this.buildAccommodations(tripId);
|
||||
}
|
||||
return trip;
|
||||
}
|
||||
|
||||
/**
|
||||
* The itinerary. Days are the spine: everything dated hangs off one, which is
|
||||
* what lets a consumer join on `date` alone.
|
||||
*
|
||||
* The per-day children are fetched once for the whole trip and grouped in memory
|
||||
* rather than queried per day — a two-week trip would otherwise cost 42 round
|
||||
* trips for the same rows.
|
||||
*/
|
||||
private buildDays(tripId: number, include: PublicApiInclude[]): PublicApiDay[] {
|
||||
const days = this.db.all<DayRow>(
|
||||
`SELECT id, day_number, date, title, notes
|
||||
FROM days WHERE trip_id = ? ORDER BY day_number ASC`,
|
||||
tripId,
|
||||
);
|
||||
if (days.length === 0) return [];
|
||||
|
||||
const placesByDay = include.includes('places') ? this.placesByDay(tripId) : new Map();
|
||||
const notesByDay = include.includes('notes') ? this.dayNotesByDay(tripId) : new Map();
|
||||
const reservationsByDay = include.includes('reservations')
|
||||
? this.reservationsByDay(tripId)
|
||||
: new Map();
|
||||
|
||||
return days.map((day) => ({
|
||||
date: day.date,
|
||||
day_number: day.day_number,
|
||||
title: day.title ?? null,
|
||||
notes: day.notes ?? null,
|
||||
places: placesByDay.get(day.id) ?? [],
|
||||
day_notes: notesByDay.get(day.id) ?? [],
|
||||
reservations: reservationsByDay.get(day.id) ?? [],
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Places in the order the traveller planned to visit them.
|
||||
*
|
||||
* `order_index` decides the sequence and is then dropped: it is a storage detail
|
||||
* that only means something relative to its siblings, and an array already
|
||||
* carries order.
|
||||
*/
|
||||
private placesByDay(tripId: number): Map<number, PublicApiPlace[]> {
|
||||
const rows = this.db.all<PlaceRow>(
|
||||
`SELECT da.day_id,
|
||||
p.name, p.address, p.lat, p.lng, p.place_time, p.end_time,
|
||||
p.duration_minutes, p.notes, p.transport_mode,
|
||||
c.name AS category
|
||||
FROM day_assignments da
|
||||
JOIN places p ON p.id = da.place_id
|
||||
LEFT JOIN categories c ON c.id = p.category_id
|
||||
WHERE p.trip_id = ?
|
||||
ORDER BY da.day_id ASC, da.order_index ASC`,
|
||||
tripId,
|
||||
);
|
||||
return groupBy(rows, (r) => r.day_id, (r) => ({
|
||||
name: r.name,
|
||||
address: r.address ?? null,
|
||||
lat: r.lat ?? null,
|
||||
lng: r.lng ?? null,
|
||||
time: r.place_time ?? null,
|
||||
end_time: r.end_time ?? null,
|
||||
duration_minutes: r.duration_minutes ?? null,
|
||||
category: r.category ?? null,
|
||||
notes: r.notes ?? null,
|
||||
transport_mode: r.transport_mode ?? null,
|
||||
}));
|
||||
}
|
||||
|
||||
private dayNotesByDay(tripId: number): Map<number, PublicApiDayNote[]> {
|
||||
const rows = this.db.all<DayNoteRow>(
|
||||
`SELECT day_id, text, time
|
||||
FROM day_notes WHERE trip_id = ?
|
||||
ORDER BY day_id ASC, sort_order ASC`,
|
||||
tripId,
|
||||
);
|
||||
return groupBy(rows, (r) => r.day_id, (r) => ({
|
||||
text: r.text,
|
||||
time: r.time ?? null,
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Bookings, reported on their starting day.
|
||||
*
|
||||
* A reservation may span days (`end_day_id`), but it is listed once rather than
|
||||
* repeated on each — a consumer that sees the same flight on three days has no
|
||||
* way to tell that from three flights.
|
||||
*/
|
||||
private reservationsByDay(tripId: number): Map<number, PublicApiReservation[]> {
|
||||
const rows = this.db.all<ReservationRow>(
|
||||
`SELECT day_id, type, title, location, reservation_time, reservation_end_time,
|
||||
status, notes
|
||||
FROM reservations
|
||||
WHERE trip_id = ? AND day_id IS NOT NULL
|
||||
ORDER BY day_id ASC, reservation_time ASC`,
|
||||
tripId,
|
||||
);
|
||||
return groupBy(rows, (r) => r.day_id, (r) => ({
|
||||
type: r.type ?? null,
|
||||
title: r.title ?? null,
|
||||
location: r.location ?? null,
|
||||
time: r.reservation_time ?? null,
|
||||
end_time: r.reservation_end_time ?? null,
|
||||
status: r.status ?? null,
|
||||
notes: r.notes ?? null,
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Accommodations with their date range resolved from the start/end day rows.
|
||||
*
|
||||
* Stored as day ids, reported as ISO dates: a consumer has no way to look up a
|
||||
* TREK day id, and the dates are what it actually needs to match its own nights.
|
||||
*/
|
||||
private buildAccommodations(tripId: number): PublicApiAccommodation[] {
|
||||
const rows = this.db.all<AccommodationRow>(
|
||||
`SELECT p.name, p.address, p.lat, p.lng,
|
||||
ds.date AS start_date, de.date AS end_date,
|
||||
a.check_in, a.check_out, a.notes
|
||||
FROM day_accommodations a
|
||||
LEFT JOIN places p ON p.id = a.place_id
|
||||
LEFT JOIN days ds ON ds.id = a.start_day_id
|
||||
LEFT JOIN days de ON de.id = a.end_day_id
|
||||
WHERE a.trip_id = ?
|
||||
ORDER BY ds.date ASC`,
|
||||
tripId,
|
||||
);
|
||||
return rows.map((r) => ({
|
||||
name: r.name ?? null,
|
||||
address: r.address ?? null,
|
||||
lat: r.lat ?? null,
|
||||
lng: r.lng ?? null,
|
||||
start_date: r.start_date ?? null,
|
||||
end_date: r.end_date ?? null,
|
||||
check_in: r.check_in ?? null,
|
||||
check_out: r.check_out ?? null,
|
||||
notes: r.notes ?? null,
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
function toTripSummary(row: TripRow): PublicApiTripSummary {
|
||||
return {
|
||||
id: row.id,
|
||||
title: row.title,
|
||||
description: row.description ?? null,
|
||||
start_date: row.start_date ?? null,
|
||||
end_date: row.end_date ?? null,
|
||||
currency: row.currency ?? null,
|
||||
archived: row.is_archived === 1,
|
||||
};
|
||||
}
|
||||
|
||||
function groupBy<Row, Out>(
|
||||
rows: Row[],
|
||||
key: (row: Row) => number,
|
||||
map: (row: Row) => Out,
|
||||
): Map<number, Out[]> {
|
||||
const grouped = new Map<number, Out[]>();
|
||||
for (const row of rows) {
|
||||
const id = key(row);
|
||||
const bucket = grouped.get(id);
|
||||
if (bucket) bucket.push(map(row));
|
||||
else grouped.set(id, [map(row)]);
|
||||
}
|
||||
return grouped;
|
||||
}
|
||||
|
||||
interface TripRow {
|
||||
id: number;
|
||||
title: string;
|
||||
description: string | null;
|
||||
start_date: string | null;
|
||||
end_date: string | null;
|
||||
currency: string | null;
|
||||
is_archived: number | null;
|
||||
}
|
||||
|
||||
interface DayRow {
|
||||
id: number;
|
||||
day_number: number;
|
||||
date: string;
|
||||
title: string | null;
|
||||
notes: string | null;
|
||||
}
|
||||
|
||||
interface PlaceRow {
|
||||
day_id: number;
|
||||
name: string;
|
||||
address: string | null;
|
||||
lat: number | null;
|
||||
lng: number | null;
|
||||
place_time: string | null;
|
||||
end_time: string | null;
|
||||
duration_minutes: number | null;
|
||||
notes: string | null;
|
||||
transport_mode: string | null;
|
||||
category: string | null;
|
||||
}
|
||||
|
||||
interface DayNoteRow {
|
||||
day_id: number;
|
||||
text: string;
|
||||
time: string | null;
|
||||
}
|
||||
|
||||
interface ReservationRow {
|
||||
day_id: number;
|
||||
type: string | null;
|
||||
title: string | null;
|
||||
location: string | null;
|
||||
reservation_time: string | null;
|
||||
reservation_end_time: string | null;
|
||||
status: string | null;
|
||||
notes: string | null;
|
||||
}
|
||||
|
||||
interface AccommodationRow {
|
||||
name: string | null;
|
||||
address: string | null;
|
||||
lat: number | null;
|
||||
lng: number | null;
|
||||
start_date: string | null;
|
||||
end_date: string | null;
|
||||
check_in: string | null;
|
||||
check_out: string | null;
|
||||
notes: string | null;
|
||||
}
|
||||
Reference in New Issue
Block a user