samchon / typia

Super-fast/easy runtime validators and serializers via transformation
https://typia.io/
MIT License
4.45k stars 153 forks source link

How to use typia with hono framework, I get error Uncaught Error: Error on typia.createValidate(): no transform has been configured. #1177

Closed tin-pham closed 1 month ago

tin-pham commented 1 month ago

Question

Hono have a page where it can use with typia, but I can't seem make this to work. https://github.com/honojs/middleware/tree/main/packages/typia-validator

Here is how I did it 1) Setup a normal hono app using the Getting Started: https://hono.dev/docs/getting-started/basic 2) Install typia

npm install typia @hono/typia-validator

3) Add some typia validation code according to hono doc: https://github.com/honojs/middleware/tree/main/packages/typia-validator 3) Run npx typia setup 4) Run npm run dev (It will run wrangler dev)

Here is my full code:

// blogs.controller.ts
import { Hono } from 'hono'
import type { BLOG } from './blogs.interface'
import { blogValidate } from './blogs.validate'

const blogs: BLOG[] = []

const blogController = new Hono()

blogController.get('/blogs', (c) => c.json({ data: blogs }))

blogController.get('/blogs/:id', (c) => {
    const { id } = c.req.param()
    const blog = blogs.find((data) => data.id === parseInt(id))
    return c.json(blog || { message: 'Blog not found' })
})

blogController.post('/blogs', blogValidate, async (c) => {
    const body = c.req.valid('json') as BLOG

    const newBlog: BLOG = {
        id: blogs.length + 1,
        title: body.title,
        content: body.content,
    }

    blogs.push(newBlog)
    return c.json(newBlog)
})

export { blogController }
// blogs.validate.ts
import { typiaValidator } from '@hono/typia-validator'
import typia from 'typia'
import { createMiddleware } from 'hono/factory'

export type BLOG = {
    id: number;
    title: string;
    content: string;
};

export const validate = typia.createValidate<BLOG>()

export const blogValidate = createMiddleware(
    typiaValidator('json', validate, (result, c) => {
        if (!result.success) {
            return c.json({ status: 400, message: 'Invalid data' })
        }
    }),
)

It will cause this error

✘ [ERROR] service core:user:hono-app: Uncaught Error: Error on typia.createValidate(): no transform has been configured. Read and follow https://typia.io/docs/setup please.

I try to search everywhere but it can't seem to work The closest discussion is this: https://github.com/samchon/typia/issues/812, but nothing relate to my problem.

ryoppippi commented 1 month ago

Can you read the error message? Have you EVER read the documantaion? You haven't configured transformation. Therefore, the code causes error. So you have three choices.

tin-pham commented 1 month ago

Thanks, i got it to work with the second choice, sorry for you inconvenient

ryoppippi commented 1 month ago

No worries! Cheers