Skip to content

Commit

Permalink
feat(effect-validator): use array formatting for errors (#718)
Browse files Browse the repository at this point in the history
* feat(effect-validator): use array formatting for errors

* add test for `error`

* make it as `minor`

---------

Co-authored-by: Yusuke Wada <yusuke@kamawada.com>
  • Loading branch information
shokiw and yusukebe authored Oct 2, 2024
1 parent 1ed5c7d commit 80da4aa
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/hot-pumas-destroy.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@hono/effect-validator': minor
---

format errors with array formatting for improved readability
4 changes: 3 additions & 1 deletion packages/effect-validator/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { ArrayFormatter } from '@effect/schema'
import * as S from '@effect/schema/Schema'
import { Either } from 'effect'
import type { Env, Input, MiddlewareHandler, ValidationTargets } from 'hono'
Expand Down Expand Up @@ -45,7 +46,8 @@ export const effectValidator = <
const result = S.decodeUnknownEither(schema)(value)

return Either.match(result, {
onLeft: (error) => c.json({ success: false, error: JSON.parse(JSON.stringify(error)) }, 400),
onLeft: (error) =>
c.json({ success: false, error: ArrayFormatter.formatErrorSync(error) }, 400),
onRight: (data) => {
c.req.addValidatedData(target, data as object)
return data
Expand Down
5 changes: 4 additions & 1 deletion packages/effect-validator/test/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { ArrayFormatter } from '@effect/schema'
import { Schema as S } from '@effect/schema'
import { Hono } from 'hono'
import type { StatusCode } from 'hono/utils/http-status'
Expand Down Expand Up @@ -103,8 +104,10 @@ describe('Basic', () => {
expect(res).not.toBeNull()
expect(res.status).toBe(400)

const data = (await res.json()) as { success: boolean }
const data = await res.json<{ success: boolean; error: ArrayFormatter.Issue[] }>()
expect(data.success).toBe(false)
expect(data.error[0].path).toEqual(['age'])
expect(data.error[0].message).toBeDefined()
})
})

Expand Down

0 comments on commit 80da4aa

Please sign in to comment.