Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

1.9 KB
Raw Blame
import type { Tag, TripTagCreateRequest, TripTagListResponse, TripTagUpdateRequest } from '@trek/shared';

import { tripTagsApi } from '../api/tripTags';
import { cachedTripTags, cacheTripTags } from '../db/cacheTripTags';
import { withTripTag } from '../utils/placeTags';
import { requireOnline } from './onlineOnly';
import { onlineThenCache } from './withOfflineFallback';

/**
 * The tags a trip owns. Reading them works offline, from the list the device last
 * read. Adding one is online only, on purpose: the place it is then put on is saved
 * with the tag's id, and a queued place cannot name a tag the server has not made.
 * Putting a tag the trip already has on a place is the place's own write, which the
 * offline queue holds like any other.
 */
export const tripTagRepo = {
  async list(tripId: number | string): Promise<TripTagListResponse> {
    const id = Number(tripId);
    return onlineThenCache(
      async () => {
        const result = await tripTagsApi.list(id);
        await cacheTripTags(id, result.tags);
        return result;
      },
      async () => ({ tags: await cachedTripTags(id) })
    );
  },

  /** The new tag, or the one the trip already has under that name. */
  async create(tripId: number | string, body: TripTagCreateRequest): Promise<Tag> {
    requireOnline();
    const id = Number(tripId);
    const { tag } = await tripTagsApi.create(id, body);
    await cacheTripTags(id, withTripTag(await cachedTripTags(id), tag));
    return tag;
  },

  /** Renames or recolours a tag of the trip. Online only, like adding one: the tag is the trip's, not a place's own write. */
  async update(tripId: number | string, tagId: number, body: TripTagUpdateRequest): Promise<Tag> {
    requireOnline();
    const id = Number(tripId);
    const { tag } = await tripTagsApi.update(id, tagId, body);
    await cacheTripTags(id, withTripTag(await cachedTripTags(id), tag));
    return tag;
  },
};