跳至內容

Azure Functions

Azure Functions 是 Microsoft Azure 提供的無伺服器平台。您可以在事件發生時執行程式碼,並且它會自動管理底層的運算資源。

Hono 最初並非為 Azure Functions 設計。但透過 Azure Functions Adapter,它也可以在其上運行。

它適用於在 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 Adapter

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. 執行

在本機執行開發伺服器。然後,在您的網頁瀏覽器中存取 https://127.0.0.1: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 Cloud 中的函數應用程式。將 <YourFunctionAppName> 取代為您的應用程式名稱。

sh
func azure functionapp publish <YourFunctionAppName>

依 MIT 授權發布。