From af4642d449810fbc66068d194df579ac2b309aa0 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Fri, 26 Jun 2026 00:45:49 -0500 Subject: [PATCH] feat: JsonTransformer and error-to-response mapping --- src/transformers.ts | 21 +++++++++++++++++++++ test/transformers.test.ts | 23 +++++++++++++++++++++++ 2 files changed, 44 insertions(+) create mode 100644 src/transformers.ts create mode 100644 test/transformers.test.ts diff --git a/src/transformers.ts b/src/transformers.ts new file mode 100644 index 0000000..b208385 --- /dev/null +++ b/src/transformers.ts @@ -0,0 +1,21 @@ +import { isHttpError, Redirect } from './signals'; +import type { TransformerFn } from './metadata'; + +export const JsonTransformer: TransformerFn = (value) => ({ + status: 200, + headers: { 'content-type': 'application/json' }, + body: JSON.stringify(value), +}); + +export function errorToResponse(e: unknown): { status: number; headers: Record; body: string } { + if (isHttpError(e)) { + const headers: Record = { 'content-type': 'application/json' }; + if (e instanceof Redirect) headers.location = e.location; + return { status: e.status, headers, body: JSON.stringify({ error: e.message }) }; + } + return { + status: 500, + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ error: 'Internal Server Error' }), + }; +} diff --git a/test/transformers.test.ts b/test/transformers.test.ts new file mode 100644 index 0000000..fa3909d --- /dev/null +++ b/test/transformers.test.ts @@ -0,0 +1,23 @@ +import { expect, test } from 'vitest'; +import { JsonTransformer, errorToResponse } from '../src/transformers'; +import { Unauthorized, Redirect } from '../src/signals'; + +test('JsonTransformer serializes value with json content-type', () => { + expect(JsonTransformer({ a: 1 })).toEqual({ + status: 200, headers: { 'content-type': 'application/json' }, body: '{"a":1}', + }); +}); + +test('errorToResponse maps HttpError to its status', () => { + const r = errorToResponse(new Unauthorized('nope')); + expect(r.status).toBe(401); + expect(JSON.parse(r.body)).toEqual({ error: 'nope' }); +}); + +test('errorToResponse sets location for Redirect', () => { + expect(errorToResponse(new Redirect('/login')).headers.location).toBe('/login'); +}); + +test('unknown error becomes 500', () => { + expect(errorToResponse(new Error('boom')).status).toBe(500); +});