Skip to content

Commit

Permalink
fix(actions): better runtime check for invalid usages
Browse files Browse the repository at this point in the history
  • Loading branch information
ematipico committed Nov 8, 2024
1 parent e10b03e commit 9264811
Show file tree
Hide file tree
Showing 4 changed files with 28 additions and 1 deletion.
14 changes: 14 additions & 0 deletions .changeset/dull-lemons-check.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
---
'astro': patch
---

Fixes a case where Astro allowed to call an action without using `Astro.callAction`. This is now invalid, and Astro will show a proper error.

```diff
---
import { actions } from "astro:actions";

-const result = actions.getUser({ userId: 123 });
+const result = Astro.callAction(actions.getUser, { userId: 123 });
---
```
3 changes: 2 additions & 1 deletion packages/astro/src/actions/runtime/virtual/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,8 @@ export function defineAction<
: getJsonServerHandler(handler, inputSchema);

async function safeServerHandler(this: ActionAPIContext, unparsedInput: unknown) {
if (typeof this === 'function') {
// The ActionAPIContext should always contain the `params` property
if (typeof this === 'function' || !('params' in this)) {
throw new AstroError(ActionCalledFromServerError);
}
return callSafely(() => serverHandler(unparsedInput, this));
Expand Down
6 changes: 6 additions & 0 deletions packages/astro/test/actions.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,12 @@ describe('Astro Actions', () => {
assert.equal(data, 'Hello, ben!');
}
});

it('Should fail when calling an action without using Astro.callAction', async () => {
const res = await fixture.fetch('/invalid/');
const text = await res.text();
assert.match(text, /ActionCalledFromServerError/);
});
});

describe('build', () => {
Expand Down
6 changes: 6 additions & 0 deletions packages/astro/test/fixtures/actions/src/pages/invalid.astro
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
import { actions } from "astro:actions";
// this is invalid, it should fail
const result = await actions.imageUploadInChunks();
---

0 comments on commit 9264811

Please sign in to comment.