跳转到正文

Fastly Compute ​

Fastly Compute 是先进的边缘计算系统,可以在 Fastly 全球边缘网络上运行用你喜爱的语言编写的代码。Hono 也能在 Fastly Compute 上运行。

使用 Fastly CLI,可以在本地开发应用,并通过几个命令发布。CLI 会随模板自动安装在本地。

1. 初始化 ​

Fastly Compute 有可用的项目模板。 使用「create-hono」命令开始创建项目。 本示例选择 fastly 模板。

sh
npm create hono@latest my-app
sh
yarn create hono my-app
sh
pnpm create hono my-app
sh
bun create hono@latest my-app
sh
deno init --npm hono my-app

进入 my-app 并安装依赖。

sh
cd my-app
npm i
sh
cd my-app
yarn
sh
cd my-app
pnpm i
sh
cd my-app
bun i

2. Hello World ​

编辑 src/index.ts:

ts
// src/index.ts
import { Hono } from 'hono'
import { fire } from '@fastly/hono-fastly-compute'

const app = new Hono()

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

fire(app)

NOTE

在应用顶层使用 @fastly/hono-fastly-compute' 的 fire(或 buildFire())时,适合使用来自 'hono' 而非 'hono/quick' 的 Hono,因为 fire 会使路由器在应用初始化阶段构建内部数据。

3. 运行 ​

在本地运行开发服务器,然后在浏览器中访问 http://localhost:7676。

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

4. 部署 ​

要构建应用并部署到 Fastly 账户,请输入以下命令。首次部署应用时,会提示你在账户中创建新服务。

如果还没有账户,必须先创建 Fastly 账户。

sh
npm run deploy
sh
yarn deploy
sh
pnpm run deploy
sh
bun run deploy

绑定 ​

在 Fastly Compute 中,可以绑定 Fastly 平台资源,例如 KV 存储、配置存储、机密存储、后端、访问控制列表、命名日志流和环境变量。可以通过 c.env 访问它们,并获得各自的 SDK 类型。

要使用这些绑定,请从 @fastly/hono-fastly-compute 中导入 buildFire,而非 fire。定义绑定并将其传给 buildFire(),以获得 fire。然后在构造 Hono 时,使用 fire.Bindings 定义 Env 类型。

ts
// src/index.ts
import { buildFire } from '@fastly/hono-fastly-compute'

const fire = buildFire({
  siteData: 'KVStore:site-data', // I have a KV Store named "site-data"
})

const app = new Hono<{ Bindings: typeof fire.Bindings }>()

app.put('/upload/:key', async (c, next) => {
  // e.g., Access the KV Store
  const key = c.req.param('key')
  await c.env.siteData.put(key, c.req.body)
  return c.text(`Put ${key} successfully!`)
})

fire(app)

基于 MIT 许可证发布。