upend/ui/src/lib/entity.ts

85 lines
2.9 KiB
TypeScript
Raw Normal View History

import { IEntry, ListingResult } from "@/types/base";
import { fetcher } from "@/utils";
import useSWRV from "swrv";
2021-06-07 00:40:07 +02:00
import { computed, ComputedRef, Ref } from "vue";
2021-04-04 11:58:23 +02:00
export function useEntity(address: string | (() => string)) {
const { data, error, mutate } = useSWRV<ListingResult, unknown>(
2021-04-04 11:58:23 +02:00
() => `/api/obj/${typeof address === "string" ? address : address()}`,
fetcher
);
const entries = computed(() => {
if (data?.value) {
const entries = Object.entries(data.value) as [string, IEntry][];
return entries
.sort(([_, a], [__, b]) => String(a.value.c).localeCompare(b.value.c))
.sort(([_, a], [__, b]) => String(a.value.t).localeCompare(b.value.t))
.sort(([_, a], [__, b]) => a.attribute.localeCompare(b.attribute));
} else {
return [];
}
});
const attributes = computed(() => {
2021-04-04 11:58:23 +02:00
const addr = typeof address === "string" ? address : address();
return entries.value.filter(([_, e]) => e.entity === addr);
});
const backlinks = computed(() => {
2021-04-04 11:58:23 +02:00
const addr = typeof address === "string" ? address : address();
return entries.value.filter(([_, e]) => e.entity !== addr);
});
return {
entries,
attributes,
backlinks,
data,
error,
mutate
}
2021-06-07 00:40:07 +02:00
}
interface EntityIdentification {
type: string;
value: string;
}
export function identify(attributes: ComputedRef<[string, IEntry][]>): ComputedRef<EntityIdentification[]> {
// Get all identities of the object
const isEntries = attributes.value
.filter(
([_, entry]) => entry.attribute === "IS"
).map(([_, entry]) => entry.value.c);
// Out of those, retrieve their TYPE_ID entries
const idAttributes: [string, Ref<ListingResult | undefined>][] = isEntries.map((type) => {
const { data: listing } = useSWRV<ListingResult, unknown>(() => {
return `/api/obj?query=(matches "${type}" "TYPE_ID" ?)`;
}, fetcher);
return [type, listing];
});
// Finally, filter own object's attributes according to TYPE_IDs
return computed(() => {
// For each identity
return idAttributes
.filter(([_, listing]) => Boolean(listing.value))
.map(([type, listing]) => {
// And each associated TYPE_ID attribute...
return Object.values(listing.value || {}).map((idEntry) => {
// return own matchin attributes
return attributes.value
.filter(([_, e]) => e.attribute === idEntry.value.c)
.map(([_, attr]) => {
return {
type,
value: attr.value.c
}
})
}).flat();
}).flat();
});
}