upend/webui/src/lib/entity.ts

77 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];
}
2021-11-11 23:37:42 +01:00
export function query(query: () => string) {
2022-01-28 16:46:08 +01:00
const queryString = typeof query === "string" ? query : query();
2021-11-11 23:37:42 +01:00
console.debug(`Querying: ${queryString}`);
const { data, error, revalidate } = useSWR<ListingResult, unknown>(
() => `/api/obj?query=${encodeURIComponent(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) {
const url = `/api/obj?query=${query}`;
if (!inFlightRequests[url]) {
console.debug(`Querying: ${query}`);
2022-01-28 16:46:08 +01:00
inFlightRequests[url] = new Promise((resolve, reject) => {
fetch(url, { keepalive: true })
.then(async (response) => {
resolve(new UpListing(await response.json()));
})
.catch((err) => reject(err));
});
} else {
console.debug(`Chaining request for ${query}...`);
}
return await inFlightRequests[url];
2021-11-11 23:37:42 +01:00
} else {
console.debug(`Returning cached: ${query}`);
return cacheResult;
}
}