This commit is contained in:
lilnasy 2023-10-10 20:21:58 +00:00
parent 89fbeb34b8
commit ae8bca661a
No known key found for this signature in database
GPG key ID: B09B8AE8D3751F1F
5 changed files with 29 additions and 5 deletions

View file

@ -0,0 +1,6 @@
import { defineMiddleware } from 'astro:middleware';
export const onRequest = defineMiddleware(({ url, locals }, next) => {
if (url.pathname === "/from-astro-middleware") locals.foo = "baz";
return next();
})

View file

@ -1,6 +1,6 @@
export async function post({ locals }) {
let out = { ...locals };
export async function POST({ locals }) {
const out = { ...locals };
return new Response(JSON.stringify(out), {
headers: {

View file

@ -0,0 +1,4 @@
---
const { foo } = Astro.locals;
---
<h1>{foo}</h1>

View file

@ -15,11 +15,10 @@ describe('API routes', () => {
await fixture.build();
});
it('Can render locals in page', async () => {
it('Can use locals added by node middleware', async () => {
const { handler } = await import('./fixtures/locals/dist/server/entry.mjs');
let { req, res, text } = createRequestAndResponse({
method: 'POST',
url: '/foo',
url: '/from-node-middleware',
});
let locals = { foo: 'bar' };
@ -32,6 +31,21 @@ describe('API routes', () => {
expect(html).to.contain('<h1>bar</h1>');
});
it('Can use locals added by astro middleware', async () => {
const { handler } = await import('./fixtures/locals/dist/server/entry.mjs');
const { req, res, text } = createRequestAndResponse({
url: '/from-astro-middleware',
});
handler(req, res, () => {});
req.send();
const html = await text();
expect(html).to.contain('<h1>baz</h1>');
});
it('Can access locals in API', async () => {
const { handler } = await import('./fixtures/locals/dist/server/entry.mjs');
let { req, res, done } = createRequestAndResponse({