参考
City
City 是运行时容器,管理 Service 生命周期、鉴权和 HTTP 路由。
City 是 Downcity 的核心实例。封装了 HTTP 路由、鉴权、环境变量和数据库基础设施。
最小使用
import { CityBase } from "@downcity/city";
const base = new CityBase({ db });Service 与 Action
每个 Service 是一组 Action。通过 base.use(service) 注册:
import { Service } from "@downcity/city";
const translate = new Service({ id: "translate", name: "翻译" });
// 注册 Action
translate.action("zh2en", async (ctx) => {
return { result: await api.translate(ctx.input.text, "en") };
});
translate.action("en2zh", async (ctx) => {
return { result: await api.translate(ctx.input.text, "zh") };
});
base.use(translate);City 自动为每个 Action 生成 HTTP 路由:
POST /v1/translate/zh2en → translate.action("zh2en")
POST /v1/translate/en2zh → translate.action("en2zh")AI Service
AIService 是内置的 Service,用于管理 AI 模型:
import { AIService, Provider } from "@downcity/city";
const deepseek = new Provider("deepseek", {
baseURL: "https://api.deepseek.com/v1",
envKey: "DEEPSEEK_API_KEY",
text: myTextAction,
stream: myStreamAction,
});
const ai = new AIService();
ai.use(deepseek.model({ id: "deepseek-v4-flash", name: "DeepSeek V4 Flash" }));
base.use(ai);Action 注册选项
// 默认 POST,auth=["user"]
svc.action("zh2en", fn);
// GET action
svc.action("list", fn, { method: "GET" });
// Admin action
svc.action("remove", fn, { auth: ["admin"] });
// Guest action(免登录)
svc.action("webhook", fn, { auth: [] });Hook 三层
// Action 级 hook(只在这个 action 触发)
const zh2en = svc.action("zh2en", fn);
zh2en.before(checkBalance).after(deductFee);
// Service 级 hook(所有 action 共享)
svc.hook.before(logRequest);
// 执行顺序:
// action.before → service.before → action.run → service.after → action.after路由启动
import { serve } from "@hono/node-server";
serve({ fetch: base.router().fetch, port: 43127, hostname: "127.0.0.1" });instruction 文档聚合
City 可以直接返回当前实例的说明文档字符串:
const text = await base.instruction();这份文本会聚合:
- City 自身怎么使用
- 当前注册的 service
- 每个模块声明的 env 配置
- 服务补充的使用说明
如果你要从远程管理端读取同一份说明,可以调用:
GET /v1/base/instruction这个接口只允许管理端访问,返回 text/plain。
鉴权
City 自动处理 user_token 和 admin_secret_key 的校验。Action 默认要求 user_token;传 auth: ["admin"] 时只允许管理端访问,传 auth: [] 时表示免登录。
详见 信任边界。