Standalone Schema

Guard를 사용하여 스키마를 정의하면 스키마가 라우트에 추가됩니다. 하지만 라우트가 스키마를 제공하면 덮어쓰여집니다:
typescript
import { Elysia, t } from 'elysia'

new Elysia()
	.guard({
		body: t.Object({
			age: t.Number()
		})
	})
	.post(
		'/user',
		({ body }) => body,
		{
			// This will override the guard schema
			body: t.Object({
				name: t.String()
			})
		}
	)
	.listen(3000)

스키마가 라우트 스키마와 공존하도록 하려면 standalone schema로 정의할 수 있습니다:

typescript
import { Elysia, t } from 'elysia'

new Elysia()
	.guard({
		schema: 'standalone', 
		body: t.Object({
			age: t.Number()
		})
	})
	.post(
		'/user',
		// body will have both age and name property
		({ body }) => body,
		{
			body: t.Object({
				name: t.String()
			})
		}
	)
	.listen(3000)

Schema Library Interoperability

standalone schema 간의 스키마는 서로 다른 검증 라이브러리를 사용할 수 있습니다.

예를 들어 zod를 사용하여 standalone schema를 정의하고 Elysia.t를 사용하여 로컬 스키마를 정의하면 둘 다 상호 교환 가능하게 작동합니다.

Assignment

standalone schema를 사용하여 요청 본문에서 agename 속성을 모두 필수로 만들어 봅시다.

  1. Standalone Schema

    Let's make POST '/user' endpoint accept a body with `name` as string and `age` as number by modifying a guard schema to be a standalone schema

Show answer

가드 옵션에 schema: 'standalone'을 추가하여 standalone schema를 정의할 수 있습니다.

typescript
import { Elysia, t } from 'elysia'
import { z } from 'zod'

new Elysia()
	.guard({
		schema: 'standalone', 
		body: z.object({
			age: z.number()
		})
	})
	.post(
		'/user',
		({ body }) => body,
		{
			body: t.Object({
				name: t.String()
			})
		}
	)
	.listen(3000)
  • index.ts

Error

Error: No Elysia server is running in index.ts
Did you forget to call `.listen()`?
    at parse (file:///vercel/path0/docs/.vitepress/.temp/utils.J44kKQwQ.js:202:66)
    at file:///vercel/path0/docs/.vitepress/.temp/utils.J44kKQwQ.js:240:30
    at new Promise (<anonymous>)
    at execute (file:///vercel/path0/docs/.vitepress/.temp/utils.J44kKQwQ.js:238:49)
    at Proxy.run (file:///vercel/path0/docs/.vitepress/.temp/store.CFqL75-f.js:190:51)
    at Proxy.wrappedAction (file:///vercel/path0/node_modules/pinia/dist/pinia.mjs:1394:26)
    at setup (file:///vercel/path0/docs/.vitepress/.temp/playground.eEZCBItr.js:133:50)
    at playground_vue_vue_type_script_setup_true_lang_default.setup (file:///vercel/path0/docs/.vitepress/.temp/playground.eEZCBItr.js:438:22)
    at callWithErrorHandling (/vercel/path0/node_modules/@vue/runtime-core/dist/runtime-core.cjs.prod.js:86:19)
    at setupStatefulComponent (/vercel/path0/node_modules/@vue/runtime-core/dist/runtime-core.cjs.prod.js:6365:25)