[ PROMPT_NODE_24148 ]
Miniflare API 参考
[ SKILL_DOCUMENTATION ]
# 程序化 API
## Miniflare 类
typescript
class Miniflare {
constructor(options: MiniflareOptions);
// 生命周期
ready: Promise; // 服务器就绪时解析,返回 URL
dispose(): Promise; // 清理资源
setOptions(options: MiniflareOptions): Promise; // 重载配置
// 事件分发
dispatchFetch(url: string | URL | Request, init?: RequestInit): Promise;
getWorker(name?: string): Promise;
// 绑定访问
getBindings<Bindings = Record>(name?: string): Promise;
getCf(name?: string): Promise;
getKVNamespace(name: string): Promise;
getR2Bucket(name: string): Promise;
getDurableObjectNamespace(name: string): Promise;
getDurableObjectStorage(id: DurableObjectId): Promise;
getD1Database(name: string): Promise;
getCaches(): Promise;
getQueueProducer(name: string): Promise;
// 调试
getInspectorURL(): Promise; // Chrome DevTools 检查器 URL
}
## 事件分发
**Fetch (无 HTTP 服务器):**
js
const res = await mf.dispatchFetch("http://localhost:8787/path", {
method: "POST",
headers: { "Authorization": "Bearer token" },
body: JSON.stringify({ data: "value" }),
});
**自定义主机路由:**
js
const res = await mf.dispatchFetch("http://localhost:8787/", {
headers: { "Host": "api.example.com" },
});
**定时任务 (Scheduled):**
js
const worker = await mf.getWorker();
const result = await worker.scheduled({ cron: "30 * * * *" });
// result: { outcome: "ok", noRetry: false }
**队列 (Queue):**
js
const worker = await mf.getWorker();
const result = await worker.queue("queue-name", [
{ id: "msg1", timestamp: new Date(), body: "data", attempts: 1 },
]);
// result: { outcome: "ok", retryAll: false, ackAll: false, ... }
## 绑定访问
**环境变量:**
js
// 基础用法
const bindings = await mf.getBindings();
console.log(bindings.SECRET_KEY);
// 类型安全 (推荐):
interface Env {
SECRET_KEY: string;
API_URL: string;
KV: KVNamespace;
}
const env = await mf.getBindings();
env.SECRET_KEY; // string (已类型化!)
env.KV.get("key"); // 可使用 KVNamespace 方法
**Request.cf 对象:**
js
const cf = await mf.getCf();
console.log(cf?.colo); // "DFW"
console.log(cf?.country); // "US"
**KV:**
js
const