fix system entity registration by re-applying configs to modules

This commit is contained in:
dswbx
2025-01-17 15:46:05 +01:00
parent 9422cc5bb8
commit a6fd9f0d96
10 changed files with 112 additions and 14 deletions

View File

@@ -0,0 +1,73 @@
import { describe, expect, test } from "bun:test";
import { createApp, registries } from "../../src";
import * as proto from "../../src/data/prototype";
import { StorageLocalAdapter } from "../../src/media/storage/adapters/StorageLocalAdapter";
describe("repros", async () => {
/**
* steps:
* 1. enable media
* 2. create 'test' entity
* 3. add media to 'test'
*
* There was an issue that AppData had old configs because of system entity "media"
*/
test("registers media entity correctly to relate to it", async () => {
registries.media.register("local", StorageLocalAdapter);
const app = createApp();
await app.build();
{
// 1. enable media
const [, config] = await app.module.media.schema().patch("", {
enabled: true,
adapter: {
type: "local",
config: {
path: "./"
}
}
});
expect(config.enabled).toBe(true);
}
{
// 2. create 'test' entity
await app.module.data.schema().patch(
"entities.test",
proto
.entity("test", {
content: proto.text()
})
.toJSON()
);
expect(app.em.entities.map((e) => e.name)).toContain("test");
}
{
await app.module.data.schema().patch("entities.test.fields.files", {
type: "media",
config: {
required: false,
fillable: ["update"],
hidden: false,
mime_types: [],
virtual: true,
entity: "test"
}
});
expect(
app.module.data.schema().patch("relations.000", {
type: "poly",
source: "test",
target: "media",
config: { mappedBy: "files" }
})
).resolves.toBeDefined();
}
expect(app.em.entities.map((e) => e.name)).toEqual(["media", "test"]);
});
});

View File

@@ -1,8 +1,5 @@
import type { CreateUserPayload } from "auth/AppAuth"; import type { CreateUserPayload } from "auth/AppAuth";
import { auth } from "auth/middlewares";
import { config } from "core";
import { Event } from "core/events"; import { Event } from "core/events";
import { patternMatch } from "core/utils";
import { Connection, type LibSqlCredentials, LibsqlConnection } from "data"; import { Connection, type LibSqlCredentials, LibsqlConnection } from "data";
import { import {
type InitialModuleConfigs, type InitialModuleConfigs,

View File

@@ -130,7 +130,10 @@ export class SchemaObject<Schema extends TObject> {
//console.log("overwritePaths", this.options?.overwritePaths); //console.log("overwritePaths", this.options?.overwritePaths);
if (this.options?.overwritePaths) { if (this.options?.overwritePaths) {
const keys = getFullPathKeys(value).map((k) => path + "." + k); const keys = getFullPathKeys(value).map((k) => {
// only prepend path if given
return path.length > 0 ? path + "." + k : k;
});
const overwritePaths = keys.filter((k) => { const overwritePaths = keys.filter((k) => {
return this.options?.overwritePaths?.some((p) => { return this.options?.overwritePaths?.some((p) => {
if (typeof p === "string") { if (typeof p === "string") {

View File

@@ -115,6 +115,7 @@ export function parse<Schema extends TSchema = TSchema>(
} else if (options?.onError) { } else if (options?.onError) {
options.onError(Errors(schema, data)); options.onError(Errors(schema, data));
} else { } else {
//console.warn("errors", JSON.stringify([...Errors(schema, data)], null, 2));
throw new TypeInvalidError(schema, data); throw new TypeInvalidError(schema, data);
} }

View File

@@ -53,6 +53,8 @@ export class AppMedia extends Module<typeof mediaConfigSchema> {
index(media).on(["path"], true).on(["reference"]); index(media).on(["path"], true).on(["reference"]);
}) })
); );
this.setBuilt();
} catch (e) { } catch (e) {
console.error(e); console.error(e);
throw new Error( throw new Error(

View File

@@ -329,6 +329,9 @@ export class ModuleManager {
} }
} }
// re-apply configs to all modules (important for system entities)
this.setConfigs(configs);
// @todo: cleanup old versions? // @todo: cleanup old versions?
this.logger.clear(); this.logger.clear();

View File

@@ -8,7 +8,6 @@ import {
} from "@tabler/icons-react"; } from "@tabler/icons-react";
import { ucFirst } from "core/utils"; import { ucFirst } from "core/utils";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { TbCirclesRelation, TbSettings } from "react-icons/tb";
import { twMerge } from "tailwind-merge"; import { twMerge } from "tailwind-merge";
import { useBknd } from "ui/client/bknd"; import { useBknd } from "ui/client/bknd";
import { useBkndData } from "ui/client/schema/data/use-bknd-data"; import { useBkndData } from "ui/client/schema/data/use-bknd-data";
@@ -76,6 +75,10 @@ export function StepCreate() {
try { try {
const res = await item.run(); const res = await item.run();
setStates((prev) => [...prev, res]); setStates((prev) => [...prev, res]);
if (res !== true) {
// make sure to break out
break;
}
} catch (e) { } catch (e) {
setStates((prev) => [...prev, (e as any).message]); setStates((prev) => [...prev, (e as any).message]);
} }
@@ -147,12 +150,14 @@ const SummaryItem: React.FC<SummaryItemProps> = ({
}) => { }) => {
const [expanded, handlers] = useDisclosure(initialExpanded); const [expanded, handlers] = useDisclosure(initialExpanded);
const error = typeof state !== "undefined" && state !== true; const error = typeof state !== "undefined" && state !== true;
const done = state === true;
return ( return (
<div <div
className={twMerge( className={twMerge(
"flex flex-col border border-muted rounded bg-background mb-2", "flex flex-col border border-muted rounded bg-background mb-2",
error && "bg-red-500/20" error && "bg-red-500/20",
done && "bg-green-500/20"
)} )}
> >
<div className="flex flex-row gap-4 px-2 py-2 items-center"> <div className="flex flex-row gap-4 px-2 py-2 items-center">

View File

@@ -9,6 +9,7 @@ import {
transformObject transformObject
} from "core/utils"; } from "core/utils";
import type { MediaFieldConfig } from "media/MediaField"; import type { MediaFieldConfig } from "media/MediaField";
import { useEffect, useState } from "react";
import { useForm } from "react-hook-form"; import { useForm } from "react-hook-form";
import { useBknd } from "ui/client/bknd"; import { useBknd } from "ui/client/bknd";
import { MantineNumberInput } from "ui/components/form/hook-form-mantine/MantineNumberInput"; import { MantineNumberInput } from "ui/components/form/hook-form-mantine/MantineNumberInput";
@@ -35,14 +36,15 @@ export function TemplateMediaComponent() {
const { const {
register, register,
handleSubmit, handleSubmit,
formState: { isValid }, formState: { isValid, errors },
setValue,
watch, watch,
control control
} = useForm({ } = useForm({
mode: "onChange",
resolver: typeboxResolver(schema), resolver: typeboxResolver(schema),
defaultValues: Default(schema, state.initial ?? {}) as TCreateModalMediaSchema defaultValues: Default(schema, state.initial ?? {}) as TCreateModalMediaSchema
}); });
const [forbidden, setForbidden] = useState<boolean>(false);
const { config } = useBknd(); const { config } = useBknd();
const media_enabled = config.media.enabled ?? false; const media_enabled = config.media.enabled ?? false;
@@ -51,13 +53,16 @@ export function TemplateMediaComponent() {
name !== media_entity ? entity : undefined name !== media_entity ? entity : undefined
); );
const data = watch(); const data = watch();
const forbidden_field_names = Object.keys(config.data.entities?.[data.entity]?.fields ?? {});
useEffect(() => {
setForbidden(forbidden_field_names.includes(data.name));
}, [forbidden_field_names, data.name]);
async function handleCreate() { async function handleCreate() {
if (isValid) { if (isValid && !forbidden) {
console.log("data", data);
const { field, relation } = convert(media_entity, data); const { field, relation } = convert(media_entity, data);
console.log("state", { field, relation });
setState((prev) => ({ setState((prev) => ({
...prev, ...prev,
fields: { create: [field] }, fields: { create: [field] },
@@ -120,6 +125,13 @@ export function TemplateMediaComponent() {
data.entity ? data.entity : "the entity" data.entity ? data.entity : "the entity"
}.`} }.`}
{...register("name")} {...register("name")}
error={
errors.name?.message
? errors.name?.message
: forbidden
? `Property "${data.name}" already exists on entity ${data.entity}`
: undefined
}
/> />
</div> </div>
{/*<p>step template media</p> {/*<p>step template media</p>
@@ -129,7 +141,7 @@ export function TemplateMediaComponent() {
<ModalFooter <ModalFooter
next={{ next={{
type: "submit", type: "submit",
disabled: !isValid || !media_enabled disabled: !isValid || !media_enabled || forbidden
}} }}
prev={{ prev={{
onClick: stepBack onClick: stepBack

View File

@@ -149,8 +149,9 @@ export function Setting<Schema extends TObject = any>({
console.log("save:success", success); console.log("save:success", success);
if (success) { if (success) {
if (options?.reloadOnSave) { if (options?.reloadOnSave) {
window.location.reload(); //window.location.reload();
//await actions.reload(); await actions.reload();
setSubmitting(false);
} }
} else { } else {
setSubmitting(false); setSubmitting(false);

View File

@@ -40,6 +40,7 @@
}, },
"linter": { "linter": {
"enabled": true, "enabled": true,
"ignore": ["**/*.spec.ts"],
"rules": { "rules": {
"recommended": true, "recommended": true,
"a11y": { "a11y": {