honojs / hono

Web framework built on Web Standards
https://hono.dev
MIT License
20.59k stars 601 forks source link

Add support for CBOR #3648

Open 3w36zj6 opened 3 weeks ago

3w36zj6 commented 3 weeks ago

What is the feature you are proposing?

CBOR is a binary format for serializing objects defined in RFC 8949. It is JSON-compatible and suitable for network communications that require efficient data exchange, as well as for use in resource-constrained environments such as IoT devices.

I would be happy to assist if there is anything I can help with. If there are concerns about supporting CBOR in the Hono core package, I am considering creating a helper as third-party middleware first.

yusukebe commented 2 weeks ago

Hi @3w36zj6

It's interesting. Does it need external libraries?

EdamAme-x commented 2 weeks ago

There is quite a bit of lines... I think seems too big to incorporate as core middleware / helper https://github.com/paroga/cbor-js/blob/master/cbor.js

3w36zj6 commented 2 weeks ago

If implemented according to the definition, I believe it can be implemented without dependencies.

In fact, cbor2, the successor of cbor, has no dependencies. However, the required lines of code are longer.

yusukebe commented 2 weeks ago

@3w36zj6

I think we can use c.setRenderer and c.render like the React Renderer.

Code example:

import { Hono } from 'hono'
import { createMiddleware } from 'hono/factory'

const app = new Hono()

declare module 'hono' {
  interface ContextRenderer {
    (content: any): Response | Promise<Response>
  }
}

const renderer = createMiddleware(async (c, next) => {
  c.setRenderer((content) => {
    return c.body(encodeCBOR(content))
  })
  await next()
})

app.use(renderer)

app.get('/', (c) => {
  return c.render({ foo: 'bar' })
})

export default app

So, if the implementation is not too complicated, we may not provide the middleware and can write the instructions on our website.

3w36zj6 commented 2 weeks ago

As an example of utilizing setRenderer, I have added example code to return a CBOR response on a website: https://github.com/honojs/website/pull/532

IMO: CBOR has related RFCs such as CBOR Sequences (RFC 8742), COSE (RFC 9053), and CWT (RFC 8392). Considering future support for these, I think it would be preferable to manage reusable code and calls to other third-party middleware centrally through CBOR Middleware/Helper.