Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(actions): getActionPath() #12721

Merged
merged 9 commits into from
Dec 18, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions .changeset/wise-boxes-develop.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
---
'astro': minor
---

Exports a new `getActionPath()` helper from `astro:actions`
florian-lefebvre marked this conversation as resolved.
Show resolved Hide resolved

In most cases, calling an action as `actions.like()` is enough. But sometimes it's not enough, for example:

- You want to pass custom headers
- You want to call the actions endpoint without `fetch`, eg. using the `navigator.sendBeacon` API

That's why you can now use the `getActionPath()` helper. Pass an action to it to get the pathname (prefixed by your `based` configuration) to the action:
florian-lefebvre marked this conversation as resolved.
Show resolved Hide resolved

```ts
import { actions, getActionPath } from 'astro:actions'

const path = getActionPath(actions.like) // '/_actions/like'
```

If you intent to use this server side, remember to supply a hostname (eg. using `Astro.site`).
5 changes: 5 additions & 0 deletions packages/astro/src/actions/runtime/virtual/shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import type {
MaybePromise,
ActionAPIContext as _ActionAPIContext,
} from '../utils.js';
import type { ActionClient } from './server.js';

export type ActionAPIContext = _ActionAPIContext;
export const ACTION_QUERY_PARAMS = _ACTION_QUERY_PARAMS;
Expand Down Expand Up @@ -180,6 +181,10 @@ export function getActionQueryString(name: string) {
return `?${searchParams.toString()}`;
}

export function getActionPath(action: ActionClient<any, any, any>) {
return `${import.meta.env.BASE_URL.replace(/\/$/, '')}/_actions/${new URLSearchParams(action.toString()).get(ACTION_QUERY_PARAMS.actionName)}`;
florian-lefebvre marked this conversation as resolved.
Show resolved Hide resolved
}

export type SerializedActionResult =
| {
type: 'data';
Expand Down
24 changes: 18 additions & 6 deletions packages/astro/templates/actions.mjs
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import { ActionError, deserializeActionResult, getActionQueryString } from 'astro:actions';
import {
ActionError,
deserializeActionResult,
getActionQueryString,
getActionPath,
} from 'astro:actions';

const ENCODED_DOT = '%2E';

Expand Down Expand Up @@ -83,11 +88,18 @@ async function handleAction(param, path, context) {
headers.set('Content-Length', '0');
}
}
const rawResult = await fetch(`${import.meta.env.BASE_URL.replace(/\/$/, '')}/_actions/${path}`, {
method: 'POST',
body,
headers,
});
const rawResult = await fetch(
getActionPath({
toString() {
return path;
},
}),
{
method: 'POST',
body,
headers,
},
);
if (rawResult.status === 204) {
return deserializeActionResult({ type: 'empty', status: 204 });
}
Expand Down
16 changes: 16 additions & 0 deletions packages/astro/test/actions.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -564,6 +564,22 @@ it('Base path should be used', async () => {
await devServer.stop();
});

it('getActionPath() should return the right path', async () => {
const fixture = await loadFixture({
root: './fixtures/actions/',
adapter: testAdapter(),
base: '/base',
});
const devServer = await fixture.startDevServer();
const res = await fixture.fetch('/base/get-action-path');

assert.equal(res.ok, true);
const html = await res.text();
let $ = cheerio.load(html);
assert.equal($('[data-path]').text(), '/base/_actions/transformFormInput');
await devServer.stop();
});

/**
* Follow an expected redirect response.
*
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
import { actions, getActionPath } from "astro:actions"

const path = getActionPath(actions.transformFormInput)
---
<p data-path>{path}</p>
Loading