fix(compiler): stop error {} from swallowing response {} bugs in api blocks
Client codegen chained .then().catch(), so a .catch() after .then() caught exceptions thrown by the response body too. Switched to the two-argument then(onFulfilled, onRejected) form, whose rejection handler cannot see errors from the fulfilment handler. SSR codegen wrapped both the transport call and the response-body eval in the same try; only __wrnexusCallApi is now inside the try, and __wrnexusEvalData runs after it, outside. Also verifies (and locks in with a regression test) that GET query numbers already coerce correctly through defineEndpoint + checkField, and documents that in the typed-api-block spec.
This commit is contained in:
@@ -329,7 +329,7 @@ function apiBindings(ast: PageAst): string {
|
||||
|
||||
return ` ${JSON.stringify(block.name)}: async (input) => context.callApi(${JSON.stringify(
|
||||
block.path,
|
||||
)}, ${JSON.stringify(block.method)}, input).then((data) => { ${response} }).catch(${failure})`;
|
||||
)}, ${JSON.stringify(block.method)}, input).then((data) => { ${response} }, ${failure})`;
|
||||
});
|
||||
|
||||
return members.length ? `const api = {\n${members.join(",\n")}\n };` : "";
|
||||
|
||||
@@ -1056,12 +1056,13 @@ async function __wrnexusResolveApiBinding(
|
||||
ctx: __WrnexusContext,
|
||||
): Promise<unknown> {
|
||||
if (binding.errorBody) {
|
||||
let data: unknown;
|
||||
try {
|
||||
const data = await __wrnexusCallApi(binding.path, binding.method, ctx);
|
||||
return __wrnexusEvalData(data, binding.body, binding.helpers, ctx);
|
||||
data = await __wrnexusCallApi(binding.path, binding.method, ctx);
|
||||
} catch (err) {
|
||||
return __wrnexusEvalError(err, binding.errorBody, binding.helpers, ctx);
|
||||
}
|
||||
return __wrnexusEvalData(data, binding.body, binding.helpers, ctx);
|
||||
}
|
||||
const data = await __wrnexusCallApi(binding.path, binding.method, ctx);
|
||||
return __wrnexusEvalData(data, binding.body, binding.helpers, ctx);
|
||||
|
||||
@@ -1,7 +1,15 @@
|
||||
import { expect, test } from "bun:test";
|
||||
import { afterEach, expect, test } from "bun:test";
|
||||
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { parse } from "@wrnexus/syntax";
|
||||
import { generateTargets } from "../src/targets.ts";
|
||||
|
||||
const roots: string[] = [];
|
||||
afterEach(() => {
|
||||
for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
function browserModule(inner: string): string {
|
||||
return generateTargets(
|
||||
parse(`page Repro {
|
||||
@@ -143,6 +151,111 @@ test("a page with state api and no client api blocks still reads that state (B5)
|
||||
}).not.toThrow();
|
||||
});
|
||||
|
||||
/**
|
||||
* Builds a browser module whose `run()` function calls api.searchUsers and
|
||||
* reports the outcome through `output.report(...)` so the test can observe
|
||||
* whether the call resolved or rejected without reaching into codegen
|
||||
* internals.
|
||||
*/
|
||||
function reportingBrowserModule(apiBlock: string): string {
|
||||
return generateTargets(
|
||||
parse(`page Repro {
|
||||
client {
|
||||
${apiBlock}
|
||||
}
|
||||
|
||||
outputs {
|
||||
report(payload: any)
|
||||
}
|
||||
|
||||
functions {
|
||||
client async function run(): Promise<void> {
|
||||
try {
|
||||
const users = await api.searchUsers({ name: "Ajay" })
|
||||
output.report({ ok: true, users })
|
||||
} catch (e) {
|
||||
output.report({ ok: false, message: String(e && e.message || e) })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
view { <main><button @click="run()">go</button></main> }
|
||||
}
|
||||
`),
|
||||
).browser;
|
||||
}
|
||||
|
||||
async function importBrowserModule(source: string): Promise<any> {
|
||||
const root = mkdtempSync(join(tmpdir(), "wrnexus-client-exec-"));
|
||||
roots.push(root);
|
||||
mkdirSync(root, { recursive: true });
|
||||
const file = join(root, "page.mjs");
|
||||
writeFileSync(file, source);
|
||||
return import(`${file.replace(/\\/g, "/")}?t=${Date.now()}`);
|
||||
}
|
||||
|
||||
test("a response body error is not swallowed by the error section (client)", async () => {
|
||||
const mod = await importBrowserModule(
|
||||
reportingBrowserModule(` api searchUsers GET /api/users {
|
||||
request { parameters { name: string } }
|
||||
response {
|
||||
return data.users.missing.length
|
||||
}
|
||||
error {
|
||||
return []
|
||||
}
|
||||
}`),
|
||||
);
|
||||
|
||||
const reports: unknown[] = [];
|
||||
const context = {
|
||||
state: {},
|
||||
props: {},
|
||||
output: { report: (value: unknown) => reports.push(value) },
|
||||
server: {},
|
||||
refs: {},
|
||||
callApi: async () => ({ users: [] }),
|
||||
};
|
||||
|
||||
await mod.__wrnexusClientFunctions.run(context);
|
||||
|
||||
expect(reports).toEqual([{ ok: false, message: expect.any(String) }]);
|
||||
// The error section's own fallback ("[]" / an empty array) must not have
|
||||
// been what the caller observed -- a bug in the response body is a
|
||||
// rejection, not a silently-returned fallback value.
|
||||
expect(reports[0]).not.toEqual({ ok: true, users: [] });
|
||||
});
|
||||
|
||||
test("a genuine transport failure still runs the error section's fallback (client)", async () => {
|
||||
const mod = await importBrowserModule(
|
||||
reportingBrowserModule(` api searchUsers GET /api/users {
|
||||
request { parameters { name: string } }
|
||||
response {
|
||||
return data.users
|
||||
}
|
||||
error {
|
||||
return ["fallback"]
|
||||
}
|
||||
}`),
|
||||
);
|
||||
|
||||
const reports: unknown[] = [];
|
||||
const context = {
|
||||
state: {},
|
||||
props: {},
|
||||
output: { report: (value: unknown) => reports.push(value) },
|
||||
server: {},
|
||||
refs: {},
|
||||
callApi: async () => {
|
||||
throw Object.assign(new Error("transport failed"), { status: 500 });
|
||||
},
|
||||
};
|
||||
|
||||
await mod.__wrnexusClientFunctions.run(context);
|
||||
|
||||
expect(reports).toEqual([{ ok: true, users: ["fallback"] }]);
|
||||
});
|
||||
|
||||
test("a state field named api does not collide with the emitted api object", () => {
|
||||
const generated = generateTargets(
|
||||
parse(`page Repro {
|
||||
|
||||
@@ -167,6 +167,83 @@ test("an ssr block used in {#each} with an error section runs the error body on
|
||||
expect(html).toContain("fallback");
|
||||
});
|
||||
|
||||
test("an ssr block's response body error is not swallowed by the error section", async () => {
|
||||
const generated = generate(
|
||||
parse(`page Repro {
|
||||
ssr {
|
||||
api ssrUsers GET /api/users {
|
||||
response {
|
||||
return data.users.missing.length
|
||||
}
|
||||
error {
|
||||
return ["fallback"]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
view { <main>{#each ssrUsers as u}<p>{u}</p>{/each}</main> }
|
||||
}
|
||||
`),
|
||||
);
|
||||
|
||||
const root = mkdtempSync(join(tmpdir(), "wrnexus-ssr-response-throws-"));
|
||||
roots.push(root);
|
||||
mkdirSync(root, { recursive: true });
|
||||
const file = join(root, "page.ts");
|
||||
writeFileSync(file, generated);
|
||||
|
||||
const mod = await import(`${file.replace(/\\/g, "/")}?t=${Date.now()}`);
|
||||
|
||||
await expect(
|
||||
mod.default({
|
||||
req: { url: "http://localhost/", headers: new Headers() },
|
||||
cookies: {},
|
||||
session: {},
|
||||
localStorage: {},
|
||||
__wrnexusCallApi: async () => ({ users: [] }),
|
||||
}),
|
||||
).rejects.toThrow();
|
||||
});
|
||||
|
||||
test("an ssr block still runs the error body on a genuine transport failure", async () => {
|
||||
const generated = generate(
|
||||
parse(`page Repro {
|
||||
ssr {
|
||||
api ssrUsers GET /api/users {
|
||||
response {
|
||||
return data.users.length
|
||||
}
|
||||
error {
|
||||
return ["fallback"]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
view { <main>{#each ssrUsers as u}<p>{u}</p>{/each}</main> }
|
||||
}
|
||||
`),
|
||||
);
|
||||
|
||||
const root = mkdtempSync(join(tmpdir(), "wrnexus-ssr-transport-fails-"));
|
||||
roots.push(root);
|
||||
mkdirSync(root, { recursive: true });
|
||||
const file = join(root, "page.ts");
|
||||
writeFileSync(file, generated);
|
||||
|
||||
const mod = await import(`${file.replace(/\\/g, "/")}?t=${Date.now()}`);
|
||||
const html = await mod.default({
|
||||
req: { url: "http://localhost/", headers: new Headers() },
|
||||
cookies: {},
|
||||
session: {},
|
||||
localStorage: {},
|
||||
__wrnexusCallApi: async () => {
|
||||
throw new Error("boom");
|
||||
},
|
||||
});
|
||||
|
||||
expect(html).toContain("fallback");
|
||||
});
|
||||
|
||||
test("an ssr block used in {#each} without an error section still propagates a failure", async () => {
|
||||
const generated = generate(
|
||||
parse(`page Repro {
|
||||
|
||||
Reference in New Issue
Block a user