Files
dragonroll/frontend/app/services/LinkTargets.js
Aran Roig 1ec29121e1
Some checks failed
Test / test (push) Failing after 2s
Build and Deploy Nuxt / build (push) Successful in 1m51s
Deploy deepseek 2
2026-10-19 19:04:28 +02:00

71 lines
2.8 KiB
JavaScript

// Fetches the campaign entries a note can link to (`[[…]]`) and keeps them briefly, so the several
// notes a campaign has open share one round of requests. The rules that turn the entries into
// suggestions live in LinkAutocomplete.js; this only talks to the API.
import Server from './Server';
import { BuildLinkSuggestions } from './LinkAutocomplete';
// Long enough to spare the API while a note is being written, short enough that an entry created in
// another note shows up soon after.
const CACHE_TTL = 30 * 1000;
const cache = new Map(); // campaignId → { at, promise }
// The campaign's four lists as the API answers them. The note preview needs the entry itself (a
// character sheet, an item), not only the label the suggestion carries, so the lists are kept as
// they arrive and both readers resolve from the same round of requests.
const LIST_PATHS = {
note: { path: '/note/all', key: 'notes' },
actor: { path: '/actor/list', key: 'actors' },
item: { path: '/item/list', key: 'items' },
map: { path: '/map/list', key: 'maps' }
};
async function fetchList(campaignId, path, key) {
try {
const response = await Server().get(path, { params: { campaign: campaignId } });
if (response.data.status !== 'ok') return [];
return response.data[key] ?? [];
} catch (error) {
return [];
}
}
function LoadCampaignEntries(campaignId) {
const id = campaignId ? String(campaignId) : '';
if (!id) {
return Promise.resolve({ notes: [], actors: [], items: [], maps: [] });
}
const cached = cache.get(id);
if (cached && Date.now() - cached.at < CACHE_TTL) return cached.promise;
const promise = Promise.all(
Object.values(LIST_PATHS).map(({ path, key }) => fetchList(id, path, key))
).then(([notes, actors, items, maps]) => ({ notes, actors, items, maps }));
cache.set(id, { at: Date.now(), promise });
return promise;
}
// The campaign's linkable entries, as BuildLinkSuggestions answers. Without a campaign id there is
// nothing to offer.
function LoadLinkTargets(campaignId) {
return LoadCampaignEntries(campaignId).then((lists) => BuildLinkSuggestions(lists));
}
// The entry a link points at, for the preview the note shows on hover (and to open its sheet). The
// target is one of the suggestions `LoadLinkTargets` answered; the lists it lives in are already
// cached, so this does not make another request.
function LoadLinkEntry(campaignId, type, id) {
const list = LIST_PATHS[type];
if (!list) return Promise.resolve(null);
return LoadCampaignEntries(campaignId).then((lists) => {
return (lists[list.key] ?? []).find((entry) => String(entry._id) === String(id)) ?? null;
});
}
function ClearLinkTargets() {
cache.clear();
}
export { LoadLinkTargets, LoadLinkEntry, ClearLinkTargets };