upend/webui/src/lib/entity.ts

76 lines
2.1 KiB
TypeScript
Raw Normal View History

2021-11-11 23:37:42 +01:00
// import { useSWR } from "sswr";
import LRU from "lru-cache";
2021-12-21 14:32:47 +01:00
import { derived, Readable } from "svelte/store";
2022-01-28 16:46:08 +01:00
import { UpListing, UpObject } from "upend";
import type { ListingResult } from "upend/types";
import { useSWR } from "../util/fetch";
2021-11-11 23:37:42 +01:00
const queryOnceLRU = new LRU<string, UpListing>(128);
const inFlightRequests: { [key: string]: Promise<UpListing> } = {};
2021-11-11 23:37:42 +01:00
export function useEntity(address: string) {
const { data, error, revalidate } = useSWR<ListingResult, unknown>(
`/api/obj/${address}`
2021-11-11 23:37:42 +01:00
);
const entity: Readable<UpObject | undefined> = derived(data, ($listing) => {
if ($listing) {
const listing = new UpListing($listing);
return listing.getObject(address);
}
2021-11-11 23:37:42 +01:00
});
return {
entity,
2021-11-11 23:37:42 +01:00
error,
revalidate,
};
}
2022-01-14 22:05:17 +01:00
export async function fetchEntry(address: string) {
const response = await fetch(`/api/raw/${address}`);
const data = await response.json();
const listing = new UpListing({ address: data });
return listing.entries[0];
}
export function query(query: string) {
console.debug(`Querying: ${query}`);
2021-11-11 23:37:42 +01:00
const { data, error, revalidate } = useSWR<ListingResult, unknown>(
"/api/query",
{ method: "POST", body: query }
2021-11-11 23:37:42 +01:00
);
const result = derived(data, ($values) => {
return $values ? new UpListing($values) : undefined;
2021-11-11 23:37:42 +01:00
});
return {
result,
error,
revalidate,
};
}
export async function queryOnce(query: string): Promise<UpListing> {
2021-11-11 23:37:42 +01:00
const cacheResult = queryOnceLRU.get(query);
if (!cacheResult) {
if (!inFlightRequests[query]) {
console.debug(`Querying: ${query}`);
inFlightRequests[query] = new Promise((resolve, reject) => {
fetch("/api/query", { method: "POST", body: query, keepalive: true })
2022-01-28 16:46:08 +01:00
.then(async (response) => {
resolve(new UpListing(await response.json()));
})
.catch((err) => reject(err));
});
} else {
console.debug(`Chaining request for ${query}...`);
}
return await inFlightRequests[query];
2021-11-11 23:37:42 +01:00
} else {
console.debug(`Returning cached: ${query}`);
return cacheResult;
}
}