import { by_character, by_lurid } from '@andyburke/fsdb/organizers'; import { FSDB_COLLECTION } from '@andyburke/fsdb'; import { FSDB_INDEXER_SYMLINKS } from '@andyburke/fsdb/indexers'; /** * @typedef {object} TIMESTAMPS * @property {string} created when the event was created * @property {string} updated when the event was last updated */ /** * Event * * @property {string} id - lurid * @property {string} creator_id - id of the source user * @property {string} type - event type * @property {string} [parent_id] - optional parent event id * @property {string[]} [tags] - optional event tags * @property {Record} [data] - optional data payload of the event * @property {TIMESTAMPS} timestamps - timestamps that will be set by the server */ export type EVENT = { id: string; creator_id: string; type: string; parent_id?: string; tags?: string[]; data?: Record; timestamps: { created: string; updated: string; }; }; type ZONE_EVENT_CACHE_ENTRY = { collection: FSDB_COLLECTION; eviction_timeout: number; }; const ZONE_EVENTS: Record = {}; export function get_events_collection_for_zone(zone_id: string): FSDB_COLLECTION { ZONE_EVENTS[zone_id] = ZONE_EVENTS[zone_id] ?? { collection: new FSDB_COLLECTION({ name: `zones/${zone_id.slice(0, 14)}/${zone_id.slice(0, 34)}/${zone_id}/events`, id_field: 'id', organize: by_lurid, indexers: { creator_id: new FSDB_INDEXER_SYMLINKS({ name: 'creator_id', field: 'creator_id', to_many: true, organize: by_lurid }), tags: new FSDB_INDEXER_SYMLINKS({ name: 'tags', get_values_to_index: (event: EVENT): string[] => { return (event.tags ?? []).map((tag: string) => tag.toLowerCase()); }, to_many: true, organize: by_character }) } }), eviction_timeout: 0 }; if (ZONE_EVENTS[zone_id].eviction_timeout) { clearTimeout(ZONE_EVENTS[zone_id].eviction_timeout); } ZONE_EVENTS[zone_id].eviction_timeout = setTimeout(() => { delete ZONE_EVENTS[zone_id]; }, 60_000 * 5); return ZONE_EVENTS[zone_id].collection; } export function clear_zone_events_cache() { for (const [zone_id, cached] of Object.entries(ZONE_EVENTS)) { if (cached.eviction_timeout) { clearTimeout(cached.eviction_timeout); } delete ZONE_EVENTS[zone_id]; } }