Skip to content

Commit 2f7cf45

Browse files
committed
fix: invalid parsing body with missed fields if used object model (#1003)
1 parent 4ba6085 commit 2f7cf45

File tree

2 files changed

+30
-4
lines changed

2 files changed

+30
-4
lines changed

src/compose.ts

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1421,11 +1421,16 @@ export const composeHandler = ({
14211421
fnLiteral += `const isNotEmptyObject=c.body&&(typeof c.body==="object"&&isNotEmpty(c.body))\n`
14221422

14231423
if (hasProperty('default', validator.body)) {
1424+
// @ts-expect-error private property
1425+
const schema = validator.body.schema
14241426
const value = Value.Default(
1425-
// @ts-expect-error private property
1426-
validator.body.schema,
1427-
// @ts-expect-error private property
1428-
validator.body.schema.type === 'object' ? {} : undefined
1427+
schema,
1428+
schema.type === 'object' ||
1429+
(schema[TypeBoxSymbol.kind] === 'Import' &&
1430+
schema.$defs[schema.$ref][TypeBoxSymbol.kind] ===
1431+
'Object')
1432+
? {}
1433+
: undefined
14291434
)
14301435

14311436
const parsed =

test/validator/body.test.ts

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -795,4 +795,25 @@ describe('Body Validator', () => {
795795

796796
expect(response).toEqual({ field: { decoded: 'bar' }, foo: 'test' })
797797
})
798+
799+
it('right rejects missed field with model', async () => {
800+
const model = new Elysia().model(
801+
'user',
802+
t.Object({
803+
username: t.String(),
804+
age: t.Integer()
805+
})
806+
)
807+
808+
const app = new Elysia().use(model).post('/', ({ body }) => body, {
809+
body: 'user'
810+
})
811+
const res = await app.handle(
812+
post('/', {
813+
name: 'sucrose'
814+
})
815+
)
816+
817+
expect(res.status).toBe(422)
818+
})
798819
})

0 commit comments

Comments
 (0)