feat(places): read every place of the trips and lists in one view

A read-only overview of every place a user can reach: the saved places of
their lists and the places of their trips, viewer trips included, with tours,
tracks and the stops of a drive left out. A saved place and a trip place are
one entry only when the saved place came from that trip place, the trip is
still open to the user, and both agree (a provider id, or the same name at the
same spot); anything else stays apart. Every entry names where it comes from
and whether it may be changed there.

- GET /api/addons/collections/library/places: paged by cursor, search,
  category, kind, list, trip and status filters, counts per kind.
- GET /api/addons/collections/library/places/{trip|list}/🆔 one entry with
  what each origin keeps on its own (notes after the existing rights, labels,
  ratings, a trip's planned days, whether a stay or booking uses it).
- MCP tools list_all_places and get_library_place.

Nothing is written and nothing migrates; the rights are the existing list and
trip checks, read on every call.
This commit is contained in:
Maurice
2026-11-29 14:57:10 +01:00
parent 82165855c7
commit 0ecca2b46c
27 changed files with 2616 additions and 2 deletions
+2
View File
@@ -80,6 +80,7 @@ import { PlaceContribModule } from './place-contrib/place-contrib.module';
import { PlaceEnrichmentModule } from './place-enrichment/place-enrichment.module';
import { PlaceImportModule } from './place-import/place-import.module';
import { PlaceShadowModule } from './place-shadow/place-shadow.module';
import { PlacesLibraryModule } from './places-library/places-library.module';
import { PlacesModule } from './places/places.module';
import { PlatformModule } from './platform/platform.module';
import { SpaFallbackFilter } from './platform/spa-fallback.filter';
@@ -202,6 +203,7 @@ import { APP_FILTER, APP_GUARD, APP_INTERCEPTOR, APP_PIPE } from '@nestjs/core';
JourneyRecordingsModule,
TripJournalLinkModule,
CollectionsModule,
PlacesLibraryModule,
ShareModule,
TripInviteModule,
TransitModule,
@@ -0,0 +1,46 @@
import { ADDON_IDS } from '../../addons';
import type { User } from '../../types';
import { AddonGuard } from '../addons/addon.guard';
import { RequireAddon } from '../addons/require-addon.decorator';
import { CurrentUser } from '../auth-core/current-user.decorator';
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
import { ResponseContract } from '../common/response-contract';
import { rowId } from '../common/row-id.pipe';
import { PlacesLibraryQueryDto } from './places-library.dto';
import { PlacesLibraryService } from './places-library.service';
import { Controller, Get, Param, Query, UseGuards } from '@nestjs/common';
import { placesLibraryDetailResponseSchema, placesLibraryPageResponseSchema } from '@trek/shared';
/**
* PLC-07/PLC-08 /api/addons/collections/library/places: "All places", the
* saved places of every list and the places of every trip the user can open,
* and one of them in detail, opened from a trip place or a saved place. Two
* segments deep, so the collections' own `GET /:id` never takes the list. The
* addon guard runs first, as on every collections route, so a disabled addon
* answers 404 before any sign-in check; the service bounds every answer by the
* user's lists and trips.
*/
@Controller('api/addons/collections/library/places')
@UseGuards(AddonGuard, JwtAuthGuard)
@RequireAddon(ADDON_IDS.COLLECTIONS, 'Collections')
export class PlacesLibraryController {
constructor(private readonly library: PlacesLibraryService) {}
@Get()
@ResponseContract(placesLibraryPageResponseSchema)
async list(@CurrentUser() user: User, @Query() query: PlacesLibraryQueryDto) {
return await this.library.list({ id: user.id, role: user.role }, query);
}
@Get('trip/:id')
@ResponseContract(placesLibraryDetailResponseSchema)
async tripPlace(@CurrentUser() user: User, @Param('id', rowId('Place not found')) id: number) {
return await this.library.detail({ id: user.id, role: user.role }, 'trip', id);
}
@Get('list/:id')
@ResponseContract(placesLibraryDetailResponseSchema)
async savedPlace(@CurrentUser() user: User, @Param('id', rowId('Place not found')) id: number) {
return await this.library.detail({ id: user.id, role: user.role }, 'list', id);
}
}
@@ -0,0 +1,5 @@
import { placesLibraryQuerySchema } from '@trek/shared';
import { createZodDto } from 'nestjs-zod';
export class PlacesLibraryQueryDto extends createZodDto(placesLibraryQuerySchema) {}
@@ -0,0 +1,166 @@
import type {
LibraryAnchorRow,
LibraryCollectionPlaceRow,
LibraryPosition,
LibraryRatingRow,
LibrarySort,
LibraryTripPlaceRow,
} from '../../db/repositories/PlacesLibrary.repository';
import {
collectionStatusSchema,
PLACES_LIBRARY_SORTS,
type PlacesLibraryCategory,
type PlacesLibraryEntry,
type PlacesLibraryInfo,
type PlacesLibraryListOrigin,
type PlacesLibraryRating,
type PlacesLibraryTripOrigin,
} from '@trek/shared';
import { z } from 'zod';
/** A cursor as it is encoded: the sort it belongs to, the last entry's sort value and its key. */
const cursorSchema = z.tuple([z.enum(PLACES_LIBRARY_SORTS), z.string(), z.number().int()]);
/** The key an entry is known by: its trip place id when it has one, else its saved place id negated. */
export function entryKey(anchor: number): string {
return anchor > 0 ? `trip:${anchor}` : `list:${-anchor}`;
}
/** The position after which the next page starts, opaque to the client. */
export function encodeLibraryCursor(sort: LibrarySort, anchor: LibraryAnchorRow): string {
const value = sort === 'name' ? anchor.sort_name : anchor.sort_time;
return Buffer.from(JSON.stringify([sort, value, anchor.anchor_key])).toString('base64url');
}
/** The position a cursor names, or null for one this sort did not hand out. */
export function decodeLibraryCursor(sort: LibrarySort, cursor: string): LibraryPosition | null {
let parsed: unknown;
try {
parsed = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8'));
} catch {
return null;
}
const result = cursorSchema.safeParse(parsed);
if (!result.success || result.data[0] !== sort) return null;
return { value: result.data[1], key: result.data[2] };
}
/** The votes of one place: their mean, how many there are, and the user's own. */
export function ratingOf(rows: readonly LibraryRatingRow[], userId: number): PlacesLibraryRating {
if (rows.length === 0) return { average: null, count: 0, mine: null };
const sum = rows.reduce((total, row) => total + row.rating, 0);
return {
average: sum / rows.length,
count: rows.length,
mine: rows.find((row) => row.user_id === userId)?.rating ?? null,
};
}
type FactsRow = LibraryTripPlaceRow | LibraryCollectionPlaceRow;
function categoryOf(row: FactsRow): PlacesLibraryCategory | null {
if (row.category_id === null || row.category_name === null) return null;
return { id: row.category_id, name: row.category_name, color: row.category_color, icon: row.category_icon };
}
/** The general facts of a place as this row keeps them. */
export function infoOf(row: FactsRow): PlacesLibraryInfo {
return {
name: row.name,
address: row.address,
lat: row.lat,
lng: row.lng,
description: row.description,
website: row.website,
phone: row.phone,
image_url: row.image_url,
category: categoryOf(row),
};
}
function tripOriginOf(row: LibraryTripPlaceRow, canEdit: boolean): PlacesLibraryTripOrigin {
return {
kind: 'trip',
trip_id: row.trip_id,
trip_title: row.trip_title,
trip_start: row.trip_start,
trip_end: row.trip_end,
place_id: row.id,
can_edit: canEdit,
read_only: !canEdit,
};
}
function listOriginOf(row: LibraryCollectionPlaceRow, canEdit: boolean): PlacesLibraryListOrigin {
return {
kind: 'list',
collection_id: row.collection_id,
collection_name: row.collection_name,
collection_place_id: row.id,
status: collectionStatusSchema.parse(row.status),
can_edit: canEdit,
};
}
/** What may be done with each origin, as the service resolved it. */
export interface OriginAccess {
canEditTrip: (row: LibraryTripPlaceRow) => boolean;
canEditList: (row: LibraryCollectionPlaceRow) => boolean;
}
/** One entry's rows: its trip place where it has one, and its saved places. */
export interface EntryRows {
anchor: number;
trip: LibraryTripPlaceRow | null;
saved: LibraryCollectionPlaceRow[];
}
/**
* The rows of each anchor, in the anchors' order. An anchor whose rows went
* away between the reads (a place deleted in between) is left out.
*/
export function rowsByAnchor(
anchors: readonly number[],
trips: readonly LibraryTripPlaceRow[],
saved: readonly LibraryCollectionPlaceRow[],
): EntryRows[] {
const tripById = new Map(trips.map((row) => [row.id, row]));
return anchors.flatMap((anchor) => {
if (anchor > 0) {
const trip = tripById.get(anchor);
if (!trip) return [];
return [{ anchor, trip, saved: saved.filter((row) => row.grouped_place_id === anchor) }];
}
const own = saved.filter((row) => row.id === -anchor && row.grouped_place_id === null);
return own.length > 0 ? [{ anchor, trip: null, saved: own }] : [];
});
}
/** An entry of the list: the trip place's facts where there is one, the trip origin first. */
export function entryOf(rows: EntryRows, access: OriginAccess): PlacesLibraryEntry {
// rowsByAnchor never hands out an entry with neither a trip place nor a saved place.
const lead: FactsRow = rows.trip ?? rows.saved[0];
const origins = [
...(rows.trip ? [tripOriginOf(rows.trip, access.canEditTrip(rows.trip))] : []),
...rows.saved.map((row) => listOriginOf(row, access.canEditList(row))),
];
return {
key: entryKey(rows.anchor),
name: lead.name,
address: lead.address,
lat: lead.lat,
lng: lead.lng,
category: categoryOf(lead),
image_url: lead.image_url ?? rows.saved.find((row) => row.image_url !== null)?.image_url ?? null,
updated_at: lead.updated_at,
origins,
};
}
/** Groups rows by one numeric field, keeping their order. */
export function groupBy<T>(rows: readonly T[], keyOf: (row: T) => number): Map<number, T[]> {
const groups = new Map<number, T[]>();
for (const row of rows) groups.set(keyOf(row), [...(groups.get(keyOf(row)) ?? []), row]);
return groups;
}
@@ -0,0 +1,68 @@
import { ADDON_IDS } from '../../addons';
import { canRead, canReadTrips } from '../../mcp/scopes';
import { McpController, Tool, TOOL_ANNOTATIONS_READONLY, ok, okCompact, type McpContext } from '../../nest-mcp';
import { addonGate } from '../addons/addon-gate';
import { AddonsService } from '../addons/addons.service';
import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service';
import { PlacesLibraryService, type LibraryUser } from './places-library.service';
import {
PLACES_LIBRARY_PAGE_DEFAULT,
PLACES_LIBRARY_PAGE_MAX,
placesLibraryDetailRequestSchema,
placesLibraryQuerySchema,
type PlacesLibraryDetailRequest,
type PlacesLibraryQuery,
} from '@trek/shared';
/**
* How long a page may run as JSON. The in-app assistant cuts a tool answer at
* 40,000 characters, so a page ends before that and next_cursor goes on after
* its last entry, as list_collection_places does.
*/
const PAGE_CHARS = 30_000;
/** The list reads trips and lists alike, so a token needs to read both. */
const readsTripsAndLists = (ctx: McpContext) => canRead(ctx.scopes, 'collections') && canReadTrips(ctx.scopes);
/**
* PLC-07/PLC-08 "All places" over the same service and the same checks as
* REST: the lists and trips the user can open, read anew for every call.
*/
@McpController()
export class PlacesLibraryMcp {
constructor(
private readonly library: PlacesLibraryService,
private readonly guards: McpToolGuardsService,
// Read by the addon gate of every tool here.
readonly addons: AddonsService,
) {}
private async user(userId: number): Promise<LibraryUser> {
return { id: userId, role: (await this.guards.isAdminUser(userId)) ? 'admin' : 'user' };
}
@Tool({
name: 'list_all_places',
description: `Page through every place the user has: the saved places of every list they can open and the places of every trip they can open, by name (sort: name, the default) or last changed first (sort: updated), ${PLACES_LIBRARY_PAGE_DEFAULT} at a time unless limit says otherwise (at most ${PLACES_LIBRARY_PAGE_MAX}). Tours, tracks and road trip stops of the drive are left out; lodging counts as a place. A saved place and a trip place are one entry only when the saved place came from that trip place and both agree (the same provider id, or the same name at the same spot); otherwise they are separate entries. Each entry has a key, name, address, lat, lng, category, image_url and its origins: kind trip (trip_id, trip_title, trip_start, trip_end, place_id, can_edit, read_only) or kind list (collection_id, collection_name, collection_place_id, status, can_edit). No notes; get_library_place reads one entry in full. Filter by q (name or address), category_id, kind, collection_id, trip_id or status (a list status); a list filter and a trip filter do not go together. Next to the page: total (what every filter matches), counts (all, trip, list for q and category_id alone) and next_cursor, passed back as cursor for the next page, null on the last. A page can end before limit, so always go on at next_cursor.`,
inputSchema: placesLibraryQuerySchema.shape,
annotations: TOOL_ANNOTATIONS_READONLY,
when: addonGate(ADDON_IDS.COLLECTIONS),
access: readsTripsAndLists,
})
async listAllPlaces(input: PlacesLibraryQuery, ctx: McpContext) {
return okCompact(await this.library.list(await this.user(ctx.userId), input, { maxChars: PAGE_CHARS }));
}
@Tool({
name: 'get_library_place',
description:
'One entry of list_all_places in full, named by one of its origins: kind trip with a trip place_id, or kind list with a collection_place_id. Answers the entry with every origin, and for each origin what it keeps on its own, in the same order: info (name, address, lat, lng, description, website, phone, image_url and category as that origin stores them, so two origins may differ), notes, rating (average, count, mine), for a list its labels, for a trip the days the place is planned on (day number, date, title, time, end time) and whether a stay or a booking uses it. Changes nothing.',
inputSchema: placesLibraryDetailRequestSchema.shape,
annotations: TOOL_ANNOTATIONS_READONLY,
when: addonGate(ADDON_IDS.COLLECTIONS),
access: readsTripsAndLists,
})
async getLibraryPlace(input: PlacesLibraryDetailRequest, ctx: McpContext) {
return ok(await this.library.detail(await this.user(ctx.userId), input.kind, input.id));
}
}
@@ -0,0 +1,32 @@
import { PlacesLibraryRepository } from '../../db/repositories/PlacesLibrary.repository';
import { AddonsModule } from '../addons/addons.module';
import { CollectionsModule } from '../collections/collections.module';
import { McpSharedModule } from '../mcp-shared/mcp-shared.module';
import { PermissionsModule } from '../permissions/permissions.module';
import { TripMembershipModule } from '../trip-membership/trip-membership.module';
import { PlacesLibraryController } from './places-library.controller';
import { PlacesLibraryMcp } from './places-library.mcp';
import { PlacesLibraryService } from './places-library.service';
import { EntityManager } from '@mikro-orm/core';
import { Module } from '@nestjs/common';
/**
* PLC-07/PLC-08 "All places" under the Collections addon: the saved places of
* every list and the places of every trip the user can open, read only. The
* repository reads across both, so it backs no entity and is built here over
* the context-resolving EntityManager, the way MaintenanceModule builds its own.
*/
@Module({
imports: [AddonsModule, CollectionsModule, TripMembershipModule, PermissionsModule, McpSharedModule],
controllers: [PlacesLibraryController],
providers: [
{
provide: PlacesLibraryRepository,
useFactory: (em: EntityManager) => new PlacesLibraryRepository(em),
inject: [EntityManager],
},
PlacesLibraryService,
PlacesLibraryMcp,
],
})
export class PlacesLibraryModule {}
@@ -0,0 +1,269 @@
import {
PlacesLibraryRepository,
type LibraryArms,
type LibraryCollectionPlaceRow,
type LibraryMatch,
type LibrarySort,
type LibraryTripPlaceRow,
} from '../../db/repositories/PlacesLibrary.repository';
import { CollectionsService } from '../collections/collections.service';
import { badRequest, notFound } from '../common/domain-error';
import { PermissionsService } from '../permissions/permissions.service';
import { TripMembershipService } from '../trip-membership/trip-membership.service';
import {
decodeLibraryCursor,
encodeLibraryCursor,
entryKey,
entryOf,
groupBy,
infoOf,
ratingOf,
rowsByAnchor,
type EntryRows,
type OriginAccess,
} from './places-library.helpers';
import { Injectable } from '@nestjs/common';
import {
PLACES_LIBRARY_PAGE_DEFAULT,
type PlacesLibraryDetail,
type PlacesLibraryDetailResponse,
type PlacesLibraryEntry,
type PlacesLibraryKind,
type PlacesLibraryPageResponse,
type PlacesLibraryQuery,
} from '@trek/shared';
/** Who asks, as the permission check reads them. */
export interface LibraryUser {
id: number;
role: string;
}
/** What the user reaches right now, read anew for every call. */
interface Reach {
tripIds: number[];
collectionIds: number[];
}
interface LibraryListOptions {
/** End a page early once its entries run this long as JSON (the assistant cuts long tool answers). */
maxChars?: number;
}
const placeNotFound = () => notFound('Place not found');
/**
* PLC-07/PLC-08 "All places": the saved places of every list the user can
* open and the places of every trip they can open, read only and paged, and
* one entry in detail with what each of its origins keeps. Who sees what is
* the existing checks, asked anew for every call: the lists of
* `CollectionsService.accessibleCollectionIds`, the trips of
* `TripMembershipService.listAccessibleTripIds`, the list roles for editing a
* saved place and the trip's 'place_edit' for editing a trip place. A list or
* trip out of reach is not found, never hinted at.
*/
@Injectable()
export class PlacesLibraryService {
constructor(
private readonly repo: PlacesLibraryRepository,
private readonly collections: CollectionsService,
private readonly membership: TripMembershipService,
private readonly permissions: PermissionsService,
) {}
async list(
user: LibraryUser,
query: PlacesLibraryQuery,
options: LibraryListOptions = {},
): Promise<PlacesLibraryPageResponse> {
const sort: LibrarySort = query.sort ?? 'name';
const after = query.cursor === undefined ? null : decodeLibraryCursor(sort, query.cursor);
if (query.cursor !== undefined && after === null) {
throw badRequest('Invalid cursor: pass the next_cursor of the page before');
}
const reach = await this.reach(user.id);
const arms = armsFor(reach, query);
const match: LibraryMatch = {
search: query.q ? query.q : null,
categoryId: query.category_id ?? null,
status: query.status ?? null,
};
const facets = { ...arms, tripIds: reach.tripIds, collectionIds: reach.collectionIds };
const counts = await this.repo.countEntries(facets, { ...match, status: null });
const narrowed =
query.kind !== undefined ||
query.collection_id !== undefined ||
query.trip_id !== undefined ||
query.status !== undefined;
const total = narrowed ? (await this.repo.countEntries(arms, match)).all : counts.all;
const limit = query.limit ?? PLACES_LIBRARY_PAGE_DEFAULT;
// One entry more than the page holds says whether another page follows.
const anchors = await this.repo.pageEntries(arms, match, sort, after, limit + 1);
const candidates = anchors.slice(0, limit);
const entries = fitPage(
await this.entries(
user,
reach,
candidates.map((anchor) => anchor.anchor_key),
),
options.maxChars,
);
// The page goes on after its last entry; a place deleted between the reads leaves no gap in the order.
const lastKey = entries[entries.length - 1]?.key;
const last =
lastKey === undefined
? candidates[candidates.length - 1]
: candidates.find((anchor) => entryKey(anchor.anchor_key) === lastKey);
const more = anchors.length > limit || (last !== undefined && last !== candidates[candidates.length - 1]);
return {
entries,
total,
counts,
next_cursor: more && last ? encodeLibraryCursor(sort, last) : null,
};
}
/** One entry, opened from the trip place or the saved place `id`, with what each origin keeps. */
async detail(user: LibraryUser, kind: PlacesLibraryKind, id: number): Promise<PlacesLibraryDetailResponse> {
const reach = await this.reach(user.id);
const anchor =
kind === 'trip'
? await this.repo.findTripPlace(id, reach.tripIds)
: await this.repo.findSavedPlaceKey(id, reach.collectionIds, reach.tripIds);
if (anchor === null) throw placeNotFound();
const rows = (await this.rows(reach, [anchor]))[0];
if (!rows) throw placeNotFound();
const entry = entryOf(rows, await this.access(user, rows.trip ? [rows.trip] : [], rows.saved));
return { entry, details: await this.details(user.id, rows) };
}
private async reach(userId: number): Promise<Reach> {
const tripIds = await this.membership.listAccessibleTripIds(userId);
const collectionIds = await this.collections.accessibleCollectionIds(userId);
return { tripIds, collectionIds };
}
private async rows(reach: Reach, anchors: number[]): Promise<EntryRows[]> {
const tripPlaceIds = anchors.filter((anchor) => anchor > 0);
const savedIds = anchors.filter((anchor) => anchor < 0).map((anchor) => -anchor);
const trips = tripPlaceIds.length > 0 ? await this.repo.tripPlaces(tripPlaceIds, reach.tripIds) : [];
const saved =
anchors.length > 0 ? await this.repo.savedPlaces(reach.collectionIds, reach.tripIds, savedIds, tripPlaceIds) : [];
return rowsByAnchor(anchors, trips, saved);
}
private async entries(user: LibraryUser, reach: Reach, anchors: number[]): Promise<PlacesLibraryEntry[]> {
const rows = await this.rows(reach, anchors);
const access = await this.access(
user,
rows.flatMap((row) => (row.trip ? [row.trip] : [])),
rows.flatMap((row) => row.saved),
);
return rows.map((row) => entryOf(row, access));
}
/**
* Whether the user may change each origin: a saved place with any list role
* but viewer (assertCanEdit's rule), a trip place with 'place_edit', which
* reads the same for every trip the user owns and for every one they are a
* member of, so it is asked once for each.
*/
private async access(
user: LibraryUser,
trips: readonly LibraryTripPlaceRow[],
saved: readonly LibraryCollectionPlaceRow[],
): Promise<OriginAccess> {
const listIds = [...new Set(saved.map((row) => row.collection_id))];
const roles = listIds.length > 0 ? await this.repo.collectionRoles(user.id, listIds) : [];
const editableLists = new Set(roles.filter((role) => role.role !== 'viewer').map((role) => role.id));
const asOwner = trips.some((row) => row.trip_owner_id === user.id)
? await this.permissions.checkPermission('place_edit', user.role, user.id, user.id, false)
: false;
const asMember = trips.some((row) => row.trip_owner_id !== user.id)
? await this.permissions.checkPermission('place_edit', user.role, null, user.id, true)
: false;
return {
canEditTrip: (row) => (row.trip_owner_id === user.id ? asOwner : asMember),
canEditList: (row) => editableLists.has(row.collection_id),
};
}
/** What each origin keeps, in the entry's origin order: the trip place first, then the saved places. */
private async details(userId: number, rows: EntryRows): Promise<PlacesLibraryDetail[]> {
const details: PlacesLibraryDetail[] = [];
if (rows.trip) {
const placeIds = [rows.trip.id];
const notes = await this.repo.tripPlaceNotes(placeIds);
const ratings = await this.repo.tripPlaceRatings(placeIds);
const days = await this.repo.plannedDays(placeIds);
const booked = await this.repo.bookedPlaces(placeIds);
details.push({
kind: 'trip',
place_id: rows.trip.id,
info: infoOf(rows.trip),
notes: notes[0]?.notes ?? null,
rating: ratingOf(ratings, userId),
days: days.map((day) => ({
day_id: day.day_id,
day_number: day.day_number,
date: day.date,
title: day.title,
time: day.time,
end_time: day.end_time,
})),
has_accommodation: booked.stays.includes(rows.trip.id),
has_reservation: booked.bookings.includes(rows.trip.id),
});
}
if (rows.saved.length > 0) {
const savedIds = rows.saved.map((row) => row.id);
const notes = new Map((await this.repo.savedPlaceNotes(savedIds)).map((row) => [row.id, row.notes]));
const labels = groupBy(await this.repo.savedPlaceLabels(savedIds), (row) => row.collection_place_id);
const ratings = groupBy(await this.repo.savedPlaceRatings(savedIds), (row) => row.target_id);
for (const row of rows.saved) {
details.push({
kind: 'list',
collection_place_id: row.id,
info: infoOf(row),
notes: notes.get(row.id) ?? null,
labels: (labels.get(row.id) ?? []).map(({ id, name, color }) => ({ id, name, color })),
rating: ratingOf(ratings.get(row.id) ?? [], userId),
});
}
}
return details;
}
}
/**
* Which trips and lists the page reads. A filter on a list (its kind, one
* list, a status) leaves the trips out, a filter on a trip the lists; a list
* or trip out of reach reads as none, so it answers like an empty one.
*/
function armsFor(reach: Reach, query: PlacesLibraryQuery): LibraryArms {
const listsOnly = query.kind === 'list' || query.collection_id !== undefined || query.status !== undefined;
const tripsOnly = query.kind === 'trip' || query.trip_id !== undefined;
if (listsOnly && tripsOnly) throw badRequest('Filter by a trip or by a list, not both');
const only = (ids: number[], id: number | undefined) =>
id === undefined ? ids : ids.filter((reachable) => reachable === id);
return {
tripIds: listsOnly ? [] : only(reach.tripIds, query.trip_id),
collectionIds: tripsOnly ? [] : only(reach.collectionIds, query.collection_id),
reachableTripIds: reach.tripIds,
};
}
/** The entries in order until their JSON would pass `maxChars`; always at least one. */
function fitPage(entries: PlacesLibraryEntry[], maxChars: number | undefined): PlacesLibraryEntry[] {
if (maxChars === undefined) return entries;
const page: PlacesLibraryEntry[] = [];
let chars = 0;
for (const entry of entries) {
chars += JSON.stringify(entry).length + 1;
if (page.length > 0 && chars > maxChars) break;
page.push(entry);
}
return page;
}