11import type { APIContext , MiddlewareHandler , MiddlewareNext } from '../../@types/astro' ;
22import { AstroError , AstroErrorData } from '../errors/index.js' ;
3+ import type { EndpointOutput } from '../../@types/astro' ;
4+ import { warn } from '../logger/core.js' ;
5+ import type { Environment } from '../render' ;
6+ import { bold } from 'kleur/colors' ;
37
48/**
59 * Utility function that is in charge of calling the middleware.
@@ -36,6 +40,7 @@ import { AstroError, AstroErrorData } from '../errors/index.js';
3640 * @param responseFunction A callback function that should return a promise with the response
3741 */
3842export async function callMiddleware < R > (
43+ logging : Environment [ 'logging' ] ,
3944 onRequest : MiddlewareHandler < R > ,
4045 apiContext : APIContext ,
4146 responseFunction : ( ) => Promise < R >
@@ -56,6 +61,15 @@ export async function callMiddleware<R>(
5661 let middlewarePromise = onRequest ( apiContext , next ) ;
5762
5863 return await Promise . resolve ( middlewarePromise ) . then ( async ( value ) => {
64+ if ( isEndpointOutput ( value ) ) {
65+ warn (
66+ logging ,
67+ 'middleware' ,
68+ 'Using simple endpoints can cause unexpected issues in the chain of middleware functions.' +
69+ `\nIt's strongly suggested to use full ${ bold ( 'Response' ) } objects.`
70+ ) ;
71+ }
72+
5973 // first we check if `next` was called
6074 if ( nextCalled ) {
6175 /**
@@ -99,6 +113,10 @@ export async function callMiddleware<R>(
99113 } ) ;
100114}
101115
102- function isEndpointResult ( response : any ) : boolean {
103- return response && typeof response . body !== 'undefined' ;
116+ function isEndpointOutput ( endpointResult : any ) : endpointResult is EndpointOutput {
117+ return (
118+ ! ( endpointResult instanceof Response ) &&
119+ typeof endpointResult === 'object' &&
120+ typeof endpointResult . body === 'string'
121+ ) ;
104122}
0 commit comments