owltide/plugins/payload-client-map.ts
Hornwitser d48fb035b4
All checks were successful
/ build (push) Successful in 1m34s
/ deploy (push) Successful in 16s
Remove type from Api serialisation of ClientMap
Move the logic that converts the EntityClass of a map to a string and
then back into the class to the payload plugin in order to avoid a
circular dependency where the ClientMap needs to know the entity classes
and the entity classes needs to know the ClientMap.

The only place that doesn't know the type of the entities stored in the
client map is the payload reviver, so it makes sense to keep this logic
contained to the payload plugin.
2025-06-23 18:17:23 +02:00

34 lines
893 B
TypeScript

import { Info } from "~/shared/utils/luxon";
import { ClientEntityNew } from "~/utils/client-user";
const typeMap: Record<string, EntityClass<ClientEntityNew>> = {
"user": ClientUser,
};
const classMap = new Map(Object.entries(typeMap).map(([k, v]) => [v, k]));
export default definePayloadPlugin(() => {
definePayloadReducer(
"ClientMap",
data => {
if (!(data instanceof ClientMap)) {
return;
}
const type = classMap.get(data.EntityClass)!;
const accountStore = useAccountStore();
return {
type,
timezone: accountStore.activeTimezone,
locale: accountStore.activeLocale,
api: data.toApi(false),
};
},
);
definePayloadReviver(
"ClientMap",
({ type, timezone, locale, api }) => {
const EntityClass = typeMap[type];
const zone = Info.normalizeZone(timezone);
return ClientMap.fromApi(EntityClass, api, { zone, locale })
},
);
});