From a64075b3eb6f838db135b1efd69e638782950420 Mon Sep 17 00:00:00 2001 From: Siddharth Singh Date: Mon, 31 Mar 2025 12:22:21 +0530 Subject: [PATCH] store default policy event in db if not found in controller, handle more errors in update route --- packages/ditto/controllers/api/policies.ts | 25 ++++++++++++++++------ 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/packages/ditto/controllers/api/policies.ts b/packages/ditto/controllers/api/policies.ts index afde7d7b..1d714815 100644 --- a/packages/ditto/controllers/api/policies.ts +++ b/packages/ditto/controllers/api/policies.ts @@ -26,6 +26,8 @@ export const adminCurrentPolicyController: AppController = async (c) => { }]).then((events) => events[0]); if (current) return c.json({ mode: conf.policyMode, spec: current }); + + await relay.event(await createPolicyEvent(conf, DEFAULT_POLICY_SPEC)); return c.json({ mode: conf.policyMode, spec: DEFAULT_POLICY_SPEC }); }; @@ -44,10 +46,21 @@ export const adminUpdatePolicyController: AppController = async (c) => { "The Ditto policy mode is set to 'script'. You will not be able to use the Policy UI until you change it to 'event'.", }); } - const req = await c.req.json(); - const parsed = PolicySpecSchema.parse(req); - await relay.event(await createPolicyEvent(conf, parsed)); - return c.json({ - message: 'Settings saved successfully.', - }); + + try { + const req = await c.req.json(); + const parsed = PolicySpecSchema.parse(req); + await relay.event(await createPolicyEvent(conf, parsed)); + return c.json({ + message: 'Settings saved successfully.', + }); + } catch (error) { + if (error instanceof SyntaxError) { + return c.json({ error: 'Invalid JSON in request body' }, 400); + } + if (error instanceof z.ZodError) { + return c.json({ error: 'Invalid policy specification', details: error.errors }, 400); + } + return c.json({ error: 'Failed to update policy' }, 500); + } };