边缘计算框架HonoJs的最佳实践

803 阅读2分钟

Hono 是一个轻量级的、快速的 Web 框架,特别适合在边缘计算环境中使用。它旨在简化 Web 应用的开发,并提供高性能.

最佳实践

Hono 非常灵活,你可以根据自己的喜好编写应用程序。但是,以下是一些最佳实践,可以更好地遵循。

避免使用类似 Ruby on Rails 的 "Controllers"

尽可能地,你应该避免创建类似 Ruby on Rails 的 "Controllers"。问题在于类型。例如,如果没有编写复杂的泛型,路径参数无法在 Controller 中推断出来。

// 🙁
// 一个类似 RoR 的 Controller
const booksList = (c: Context) => {
  return c.json('list books')
}

app.get('/books', booksList)

例如,路径参数不能在 Controller 中被推断,无需编写复杂的泛型。

// 🙁
// A RoR-like Controller
const bookPermalink = (c: Context) => {
  const id = c.req.param('id') // Can't infer the path param
  return c.json(`get ${id}`)
}

因此,你不需要创建类似 RoR 的 controllers,而应该在路径定义后直接编写处理程序。

// 😃
app.get('/books/:id', (c) => {
  const id = c.req.param('id') // 可以推断路径参数
  return c.json(`get ${id}`)
})

使用 factory.createHandlers()

如果你仍然想创建一个类似 RoR 的 Controller,可以使用 hono/factory 中的 factory.createHandlers()。如果你使用这个,类型推断会正确工作。

import { createFactory } from 'hono/factory'
import { logger } from 'hono/logger'

// ...

// 😃
const factory = createFactory()

const middleware = factory.createMiddleware(async (c, next) => {
  c.set('foo', 'bar')
  await next()
})

const handlers = factory.createHandlers(logger(), middleware, (c) => {
  return c.json(c.var.foo)
})

app.get('/api', ...handlers)

构建更大的应用

使用 app.route() 构建更大的应用程序,而无需创建类似 "Ruby on Rails" 的 Controllers。如果你的应用程序有 /authors/books 端点,并且你希望将文件从 index.ts 中分离出来,创建 authors.tsbooks.ts

// authors.ts
import { Hono } from 'hono'

const app = new Hono()

app.get('/', (c) => c.json('list authors'))
app.post('/', (c) => c.json('create an author', 201))
app.get('/:id', (c) => c.json(`get ${c.req.param('id')}`))

export default app
// books.ts
import { Hono } from 'hono'

const app = new Hono()

app.get('/', (c) => c.json('list books'))
app.post('/', (c) => c.json('create a book', 201))
app.get('/:id', (c) => c.json(`get ${c.req.param('id')}`))

export default app

然后,导入它们并使用 app.route() 将它们挂载到路径 /authors/books 上。

// index.ts
import { Hono } from 'hono'
import authors from './authors'
import books from './books'

const app = new Hono()

// 😃
app.route('/authors', authors)
app.route('/books', books)

export default app

如果想使用 RPC 功能

以上代码适用于正常用例。但是,如果你想使用 RPC 功能,你可以通过如下链式调用来获得正确的类型。

// authors.ts
import { Hono } from 'hono'

const app = new Hono()
  .get('/', (c) => c.json('list authors'))
  .post('/', (c) => c.json('create an author', 201))
  .get('/:id', (c) => c.json(`get ${c.req.param('id')}`))

export default app

如果将应用程序的类型传递给 hc,它将获得正确的类型。

import app from './authors'
import { hc } from 'hono/client'

// 😃
const client = hc<typeof app>('http://localhost') // 类型正确

实际应用例子

假设你要创建一个简单的博客 API,其中包含文章列表和文章详情。你可以使用 Hono 来实现这个 API,避免使用传统的 Controllers,而是直接在路由定义后编写处理程序。

代码示例

首先,安装 Hono:

npm install hono

然后,创建一个 index.ts 文件:

// index.ts
import { Hono } from 'hono'

const app = new Hono()

// 获取文章列表
app.get('/posts', (c) => {
  const posts = [
    { id: 1, title: 'Hello Hono' },
    { id: 2, title: 'Hono is awesome' }
  ]
  return c.json(posts)
})

// 获取文章详情
app.get('/posts/:id', (c) => {
  const id = c.req.param('id')
  const post = { id: parseInt(id), title: `Post ${id}` }
  return c.json(post)
})

export default app

在这个例子中,我们直接在路由定义后编写了处理程序,避免了创建额外的 Controllers。

总结

Hono 通过其简洁的设计和高效的性能,为开发者提供了一种快速构建 Web 应用的方式. 通过遵循最佳实践,你可以更好地利用 Hono 的优势,构建出更高效、更易于维护的应用程序.