0
Fork 0
mirror of https://github.com/withastro/astro.git synced 2025-01-06 22:10:10 -05:00

Fix: allow locals access from actions (#11006)

* fix: move actions middleware to post

* fix(test): user middleware

* chore: changeset
This commit is contained in:
Ben Holmes 2024-05-13 07:23:52 -04:00 committed by GitHub
parent cb2586fa15
commit 7418bb054c
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 45 additions and 2 deletions

View file

@ -0,0 +1,5 @@
---
"astro": patch
---
Fix `locals` access from action handlers

View file

@ -29,7 +29,7 @@ export default function astroActions(): AstroIntegration {
params.addMiddleware({
entrypoint: 'astro/actions/runtime/middleware.js',
order: 'pre',
order: 'post',
});
await typegen({

View file

@ -2,6 +2,7 @@ import assert from 'node:assert/strict';
import { after, before, describe, it } from 'node:test';
import testAdapter from './test-adapter.js';
import { loadFixture } from './test-utils.js';
import * as cheerio from 'cheerio';
describe('Astro Actions', () => {
let fixture;
@ -169,5 +170,20 @@ describe('Astro Actions', () => {
assert.equal(json.success, true);
assert.equal(json.isFormData, true, 'Should receive plain FormData');
});
it('Respects user middleware', async () => {
const formData = new FormData();
formData.append('_astroAction', '/_actions/getUser');
const req = new Request('http://example.com/middleware', {
method: 'POST',
body: formData,
});
const res = await app.render(req);
assert.equal(res.ok, true);
const html = await res.text();
let $ = cheerio.load(html);
assert.equal($('#user').text(), 'Houston');
})
});
});

View file

@ -1,4 +1,4 @@
import { defineAction, z } from 'astro:actions';
import { defineAction, getApiContext, z } from 'astro:actions';
export const server = {
subscribe: defineAction({
@ -29,4 +29,11 @@ export const server = {
};
},
}),
getUser: defineAction({
accept: 'form',
handler: async () => {
const { locals } = getApiContext();
return locals.user;
}
})
};

View file

@ -0,0 +1,8 @@
import { defineMiddleware } from 'astro:middleware';
export const onRequest = defineMiddleware((ctx, next) => {
ctx.locals.user = {
name: 'Houston',
};
return next();
});

View file

@ -0,0 +1,7 @@
---
import { actions } from 'astro:actions';
const res = Astro.getActionResult(actions.getUser);
---
<h1 id="user">{res?.data?.name}</h1>