From 785c4e03d8953f3a539d49b456170ed635a355e8 Mon Sep 17 00:00:00 2001 From: TheoryOfNekomata Date: Tue, 12 Mar 2024 20:00:47 +0800 Subject: [PATCH] Improve error handling Add all validation errors. --- src/core.ts | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/src/core.ts b/src/core.ts index e643f01..b31c25d 100644 --- a/src/core.ts +++ b/src/core.ts @@ -27,6 +27,7 @@ export interface Resource { routeName?: string; dataSource: DataSource; newId(dataSource: DataSource): string | number | unknown; + schema: Parameters[0]; } interface GenerationStrategy { @@ -88,6 +89,9 @@ export const resource = (schema: Parameters[0]) => { }, get routeName() { return theRouteName; + }, + get schema() { + return schema; } }; }; @@ -150,10 +154,21 @@ const handleCreate = async ( resolve(); return; } - } catch { + + await v.parseAsync(v.object(resource.schema), bodyDeserialized, { abortEarly: false }); + } catch (err) { res.statusCode = constants.HTTP_STATUS_BAD_REQUEST; res.statusMessage = `Invalid ${resource.itemName}`; - res.end(); + + if (Array.isArray(err.issues)) { + // TODO better error reporting, localizable messages + res.end( + err.issues.map((i) => `${i.path.map((p) => p.key).join('.')}:\n${i.message}`) + .join('\n\n') + ) + } else { + res.end(); + } resolve(); return; }