upend/webui/src/lib/entity.ts

60 lines
1.3 KiB
TypeScript
Raw Normal View History

2021-11-11 23:37:42 +01:00
// import { useSWR } from "sswr";
import { derived, type Readable } from "svelte/store";
import { UpListing, UpObject } from "@upnd/upend";
import type {
ListingResult,
EntityListing,
EntityInfo,
} from "@upnd/upend/types";
import { useSWR } from "../util/fetch";
import api from "./api";
2023-06-05 12:56:33 +02:00
import debug from "debug";
const dbg = debug("kestrel:lib");
2021-11-11 23:37:42 +01:00
export function useEntity(address: string) {
2022-02-07 20:46:17 +01:00
const { data, error, revalidate } = useSWR<EntityListing, unknown>(
2023-08-01 22:02:52 +02:00
`${api.apiUrl}/obj/${address}`,
2021-11-11 23:37:42 +01:00
);
const entity: Readable<UpObject | undefined> = derived(data, ($listing) => {
if ($listing) {
2022-02-07 20:46:17 +01:00
const listing = new UpListing($listing.entries);
return listing.getObject(address);
}
2021-11-11 23:37:42 +01:00
});
2022-02-07 20:46:17 +01:00
const entityInfo: Readable<EntityInfo | undefined> = derived(
data,
($listing) => {
if ($listing) {
return $listing.entity;
}
2023-08-01 22:02:52 +02:00
},
2022-02-07 20:46:17 +01:00
);
2021-11-11 23:37:42 +01:00
return {
entity,
2022-02-07 20:46:17 +01:00
entityInfo,
2021-11-11 23:37:42 +01:00
error,
revalidate,
};
}
export function query(query: string) {
2023-06-05 12:56:33 +02:00
dbg(`Querying: ${query}`);
2021-11-11 23:37:42 +01:00
const { data, error, revalidate } = useSWR<ListingResult, unknown>(
`${api.apiUrl}/query`,
2023-08-01 22:02:52 +02:00
{ 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,
};
}