upend/webui/src/lib/entity.ts

67 lines
1.4 KiB
TypeScript
Raw Normal View History

2021-11-11 23:37:42 +01:00
// import { useSWR } from "sswr";
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
2022-02-07 20:46:17 +01:00
export type EntityInfo =
| {
t: "Hash" | "Uuid";
}
| {
t: "Attribute" | "Url";
c: string;
};
export interface EntityListing {
entity: EntityInfo;
entries: ListingResult;
}
export function useEntity(address: string) {
2022-02-07 20:46:17 +01:00
const { data, error, revalidate } = useSWR<EntityListing, unknown>(
`api/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;
}
}
);
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) {
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,
};
}