[Proposal] RPC
See original GitHub issueI’ll introduce an ultra cool feature. It will improve our developer experience. This issue is a continuation of #602.
“tRPC” is helpful for sharing the types between the server and the client. This means it makes the types an API specification. There is a request to make tRPC adapter #582 , I think it’s good to make the adapter as 3rd party middleware.
So, tPRC is great, but we can do it in a better way with Hono because we can make it “integrated”.
What we want to do are below:
- Share the request format inferred from the validation schema.
- Share the response format inferred from JSON objects that is returned in a handler.
- Implement “client” not only on the server-side.
Then, I have created those prototypes. They are not fully implemented, but they work. See the screencast:
Server-side code:
const api = new Hono()
const getRoute = api
.get('/hello', (c) => {
return c.jsonT({
messages: 'hello',
})
})
.build()
const postRoute = api
.post(
'/posts',
validator((v) => ({
id: v.json('id'),
title: v.json('title'),
})),
(c) => {
const post = c.req.valid()
return c.jsonT({ title: post.title })
}
)
.build()
export type AppType = typeof postRoute & typeof getRoute
Client-side code:
import type { AppType } from './server'
const client = new Client<AppType>('http://127.0.0.1:8787/api')
const res = await client.get('/hello')
console.log(res.messages)
const res2 = await client.json('/posts', {
id: '123',
title: 'Hello!'
})
console.log(res2.title)
The client-side needs to be considered, but this is a good idea for the server-side API. And, if developers want to use 3rd party validator like a “Zod”, they may use it.
Notes, we need to brush up on our data structures to handle types with Generics.
Isn’t it cool? I may create the PR later.
Issue Analytics
- State:
- Created 9 months ago
- Reactions:9
- Comments:13
Top GitHub Comments
You are thinking about file upload? I think each client method is a specific spec. For example client.json() is a POST request with content-type application/json. Similarly there could be a client.upload() that uses multi-part though I’m not sure that’s need for a first release to keep things simple.
Looks great! I like the API.
Some thoughts I’ve had wile working with my “type-knit” project that might be relevant here as well:
const postRoute = api .post( ‘/posts’, validator((v) => ({ id: v.json(‘id’), title: v.json(‘title’), })), © => { const post = c.req.valid() return DoClient(dostub).json(“/increment”, {title: post.title}) } ) .build() ‘’’