From 360202a8372168ef3b5acfad97b9a9ac14c99d87 Mon Sep 17 00:00:00 2001 From: Eric Crosson Date: Thu, 19 May 2022 19:34:51 -0500 Subject: [PATCH] refactor(express-wrapper): avoid using codec type-guard This refactor changes the response code path to try encoding the service function's response value with the apiSpec's response codec, and if this errors returns a 500. Previously we used the codec's type-guard as a test if the codec can encode the service function's response value, but this step will take extra time and there's no hard contract that guarantees us the type-guard returning `true` really means that the codec will be able to encode a value. Instead, we just try the dangerous deed and do our best to catch errors. --- packages/express-wrapper/src/response.ts | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/packages/express-wrapper/src/response.ts b/packages/express-wrapper/src/response.ts index 14f9c0cb..504f1648 100644 --- a/packages/express-wrapper/src/response.ts +++ b/packages/express-wrapper/src/response.ts @@ -38,13 +38,12 @@ export const defaultResponseEncoder: ResponseEncoder = ( return; } const responseCodec = route.response[status]; - if (responseCodec === undefined || !responseCodec.is(payload)) { + try { + expressRes.status(status).json(responseCodec!.encode(payload)).end(); + } catch { console.warn( "Unable to encode route's return value, did you return the expected type?", ); expressRes.status(500).end(); - return; } - - expressRes.status(status).json(responseCodec.encode(payload)).end(); };