Skip to content

Azure Functions

Azure Functions 是微软 Azure 提供的 Serverless 平台。代码可以响应事件触发执行,平台会自动管理底层计算资源。

Hono 最初并未针对 Azure Functions 设计,但借助 Azure Functions 适配器 也能在其上运行。

本指南基于运行在 Node.js 18 或以上版本的 Azure Functions V4

1. 安装 CLI

要创建 Azure Function,需要先安装 Azure Functions Core Tools

在 macOS 上:

sh
brew tap azure/functions
brew install azure-functions-core-tools@4

其他操作系统请参考以下文档:

2. 环境准备

在当前目录创建一个 TypeScript Node.js V4 项目:

sh
func init --typescript

接着修改宿主默认的路由前缀,在 host.json 的根对象中加入以下配置:

json
"extensions": {
    "http": {
        "routePrefix": ""
    }
}

INFO

Azure Functions 默认的路由前缀为 /api。如果不按上述方式修改,请确保所有 Hono 路由都以 /api 开头。

现在即可安装 Hono 与 Azure Functions 适配器:

sh
npm i @marplex/hono-azurefunc-adapter hono
sh
yarn add @marplex/hono-azurefunc-adapter hono
sh
pnpm add @marplex/hono-azurefunc-adapter hono
sh
bun add @marplex/hono-azurefunc-adapter hono

3. Hello World

创建 src/app.ts

ts
// src/app.ts
import { Hono } from 'hono'
const app = new Hono()

app.get('/', (c) => c.text('Hello Azure Functions!'))

export default app

创建 src/functions/httpTrigger.ts

ts
// src/functions/httpTrigger.ts
import { app } from '@azure/functions'
import { azureHonoHandler } from '@marplex/hono-azurefunc-adapter'
import honoApp from '../app'

app.http('httpTrigger', {
  methods: [
    // 在此加入需要支持的所有 HTTP 方法
    'GET',
    'POST',
    'DELETE',
    'PUT',
  ],
  authLevel: 'anonymous',
  route: '{*proxy}',
  handler: azureHonoHandler(honoApp.fetch),
})

4. 运行

在本地启动开发服务器,然后在浏览器访问 http://localhost:7071

sh
npm run start
sh
yarn start
sh
pnpm start
sh
bun run start

5. 部署

INFO

在部署到 Azure 之前,需要先在云环境中创建相关资源。请参考微软文档:Create supporting Azure resources for your function

首先构建项目:

sh
npm run build
sh
yarn build
sh
pnpm build
sh
bun run build

然后将项目部署到 Azure 云中的函数应用。将 <YourFunctionAppName> 替换为你的应用名称。

sh
func azure functionapp publish <YourFunctionAppName>

Released under the MIT License.