From b0a0494a2848892e8e2a5b2a940546338a05c788 Mon Sep 17 00:00:00 2001 From: kodemon Date: Fri, 18 Apr 2025 22:56:29 +0000 Subject: [PATCH] feat: add error response support to actions --- deno.json | 2 +- libraries/action.ts | 6 ++++-- libraries/api.ts | 3 +++ tests/mocks/actions.ts | 4 ++++ tests/route.test.ts | 4 ++++ 5 files changed, 16 insertions(+), 3 deletions(-) diff --git a/deno.json b/deno.json index 41ef5ae..50e76af 100644 --- a/deno.json +++ b/deno.json @@ -1,6 +1,6 @@ { "name": "@valkyr/relay", - "version": "0.1.1", + "version": "0.1.2", "exports": { ".": "./mod.ts", "./http": "./adapters/http.ts" diff --git a/libraries/action.ts b/libraries/action.ts index eca7787..e31c26f 100644 --- a/libraries/action.ts +++ b/libraries/action.ts @@ -1,5 +1,7 @@ import z, { ZodObject, ZodRawShape } from "zod"; +import { RelayError } from "./errors.ts"; + export class Action { constructor(readonly state: TActionState) {} @@ -61,5 +63,5 @@ type ActionState = { }; type ActionHandlerFn = TInput extends ZodObject - ? (input: z.infer) => TOutput extends ZodObject ? Promise> : Promise - : () => TOutput extends ZodObject ? Promise> : Promise; + ? (input: z.infer) => TOutput extends ZodObject ? Promise | RelayError> : Promise + : () => TOutput extends ZodObject ? Promise | RelayError> : Promise; diff --git a/libraries/api.ts b/libraries/api.ts index 41b8b1a..df5000b 100644 --- a/libraries/api.ts +++ b/libraries/api.ts @@ -130,6 +130,9 @@ export class Api { return toResponse(new InternalServerError(`Action '${action.state.name}' is missing handler.`)); } const output = await action.state.handle(result.data); + if (output instanceof RelayError) { + return toResponse(output); + } for (const key in output) { context[key] = output[key]; } diff --git a/tests/mocks/actions.ts b/tests/mocks/actions.ts index 036904f..62d1906 100644 --- a/tests/mocks/actions.ts +++ b/tests/mocks/actions.ts @@ -1,12 +1,16 @@ import z from "zod"; import { action } from "../../libraries/action.ts"; +import { BadRequestError } from "../../mod.ts"; export const addTwoNumbers = action .make("addTwoNumbers") .input({ a: z.number(), b: z.number() }) .output({ added: z.number() }) .handle(async ({ a, b }) => { + if (a < 0 || b < 0) { + return new BadRequestError("Invalid input numbers added"); + } return { added: a + b, }; diff --git a/tests/route.test.ts b/tests/route.test.ts index 13530f4..9090264 100644 --- a/tests/route.test.ts +++ b/tests/route.test.ts @@ -52,4 +52,8 @@ describe("Relay", () => { it("should successfully run .actions", async () => { assertEquals(await relay.get("/add-two", { a: 1, b: 1 }), 2); }); + + it("should reject .actions with error", async () => { + assertEquals(await relay.get("/add-two", { a: -1, b: 1 }), 2); + }); });