跳转到正文

Azure Functions ​

Azure Functions 是 Microsoft Azure 提供的无服务器平台。你可以在响应事件时运行代码,底层计算资源由平台自动管理。

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 对象中添加以下属性:

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

说明

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: [
    //Add all your supported HTTP methods here
    '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. 部署 ​

说明

部署到 Azure 前,需要在云基础设施中创建一些资源。请参阅 Microsoft 文档中的为函数创建支持的 Azure 资源。

构建项目以进行部署:

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

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

sh
func azure functionapp publish <YourFunctionAppName>

基于 MIT 许可证发布。