[错误] Eden Treaty 2: 当父路径部分是 HTTP 方法名称(例如 /api/post/:id) 时,动态参数无法访问
环境 elysia 1.4.30, @elysia/eden 1.4.10 Bun 1.3.14 (server), Chromium (client) 描述错误 Eden Treaty 2 无法在节点的路径以类似 HTTP 方法的名称结尾时选择动态路径参数(例如 get / post / put / delete / patch / options / head / connect / subscribe)。对于路由 GET /api/post/:id: 预期: await eden.api.post({ id: 1 }).get() → GET /api/post/1 实际: 运行时将父节点上的最后一个 post 部分视为 HTTP 方法,并触发 POST /api,该调用返回一个 Promise,因此链式调用 .get() 会抛出 .get 不是函数。使用带类型的客户端,情况更糟: eden.api.post({ id: 1 }).get() 会进行类型检查并推断正确的响应类型,因此类型和运行时在完全相同的调用上出现了分歧。 最小重现 server.ts import { Elysia, t } from 'elysia' const app = new Elysia({ prefix: '/api' }) .use( new Elysia({ prefix: '/post' }) .get('/:id', ({ params: { id } }) => ({ msg: 'ok', data: { id } }), { params: t.Object({ id: t.Integer() }) }) ) .use( new Elysia({ prefix: '/user' }) .get('/:id', ({ params: { id } }) => ({ msg: 'ok', data: { id } }), { params: t.Object({ id: t.Integer() }) }) ) ) .listen(3210) client.ts import { treaty } from '@elysia/eden' const eden = treaty('http://localhost:3210') // ✅ control: parent tail is not a method name await eden.api.user({ id: 1 }).get() → GET /api/user/1 // ❌ bug: parent tail is `post` await eden.api.post({ id: 1 }).get() → fires POST /api, then throws ".get is not a function" // 解决方案: 明确地指定该部分 await (eden.api.post as any)['1'].get() → GET /api/post/1 观察到的输出(在本地验证): 1) user({ id }).get() → 200 {"msg":"ok","data":{"id":1}} 2) post({ id }).get() 扔出: eden.api.post({ id: 1 }).get is not a function 捕获的请求: GET http://localhost:3210/api/user/1 → 200 POST http://localhost:3210/api → 404 GET http://localhost:3210/api/post/1 → 200 (解决方案) 根本原因 treaty 运行时使用以下启发式规则来决定是"动态参数选择"还是"发送请求": (从运行时代码块中精简摘录) var X = ["get","post","put","delete","patch","options","head","connect","subscribe"] apply(o, i, [s, u]) { if (!s || u || (typeof s == "object" && Object.keys(s).length !== 1) || X.includes(n.at(-1))) { let x = [...n], m = x.pop(), b = "/" + x.join("/"); // 从栈中弹出最后一个部分作为 HTTP 方法 /* ... fetch ... */ } else: dynamic segment selection (将单个值作为路径部分添加) } 执行 eden.api.post({ id: 1 }): s = { id: 1 } 是单个键对象(符合动态选择条件),但 n.at(-1) === 'post' 在 X 中,因此它会短路到 fetch 分支,并将 post 视为父 /api 节点上的 HTTP 方法。类型级树将 /api/post 模型为具有 :id 子节点的命名空间,因此出现了不匹配。 同理
内容来源: elysiajs/elysia