Test that redirects can come from middleware (#7213)

* Test that redirects can come from middleware

* Allow non-promise returns for middleware
This commit is contained in:
Matthew Phillips 2023-05-26 06:49:10 -04:00 committed by GitHub
parent 8b4d248a36
commit ef9a456f25
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 34 additions and 2 deletions

View file

@ -1805,7 +1805,7 @@ export type MiddlewareNext<R> = () => Promise<R>;
export type MiddlewareHandler<R> = (
context: APIContext,
next: MiddlewareNext<R>
) => Promise<R> | Promise<void> | void;
) => Promise<R> | R | Promise<void> | void;
export type MiddlewareResponseHandler = MiddlewareHandler<Response>;
export type MiddlewareEndpointHandler = MiddlewareHandler<Response | EndpointOutput>;

View file

@ -0,0 +1,13 @@
import { defineMiddleware } from 'astro/middleware';
export const onRequest = defineMiddleware(({ request }, next) => {
if(new URL(request.url).pathname === '/middleware-redirect/') {
return new Response(null, {
status: 301,
headers: {
'Location': '/'
}
});
}
return next();
});

View file

@ -0,0 +1,10 @@
---
---
<html>
<head>
<title>This page should have been redirected</title>
</head>
<body>
<h1>This page should have been redirected</h1>
</body>
</html>

View file

@ -14,7 +14,7 @@ describe('Astro.redirect', () => {
adapter: testAdapter(),
redirects: {
'/api/redirect': '/'
}
},
});
await fixture.build();
});
@ -67,6 +67,9 @@ describe('Astro.redirect', () => {
fixture = await loadFixture({
root: './fixtures/ssr-redirect/',
output: 'static',
experimental: {
middleware: true
},
redirects: {
'/one': '/',
'/two': '/',
@ -109,5 +112,11 @@ describe('Astro.redirect', () => {
expect(html).to.include('http-equiv="refresh');
expect(html).to.include('url=/articles/two');
});
it('Generates redirect pages for redirects created by middleware', async () => {
let html = await fixture.readFile('/middleware-redirect/index.html');
expect(html).to.include('http-equiv="refresh');
expect(html).to.include('url=/');
});
});
});