mirror of
https://github.com/withastro/astro.git
synced 2024-12-30 22:03:56 -05:00
d5277df5a4
* fix(node): Wrap request creation in try catch * chore: changeset
35 lines
1,023 B
TypeScript
35 lines
1,023 B
TypeScript
import { NodeApp } from 'astro/app/node';
|
|
import type { RequestHandler } from './types.js';
|
|
|
|
/**
|
|
* Creates a Node.js http listener for on-demand rendered pages, compatible with http.createServer and Connect middleware.
|
|
* If the next callback is provided, it will be called if the request does not have a matching route.
|
|
* Intended to be used in both standalone and middleware mode.
|
|
*/
|
|
export function createAppHandler(app: NodeApp): RequestHandler {
|
|
return async (req, res, next, locals) => {
|
|
let request;
|
|
try {
|
|
request = NodeApp.createRequest(req);
|
|
} catch (err) {
|
|
res.statusCode = 500;
|
|
res.end('Internal Server Error');
|
|
return;
|
|
}
|
|
|
|
const routeData = app.match(request);
|
|
if (routeData) {
|
|
const response = await app.render(request, {
|
|
addCookieHeader: true,
|
|
locals,
|
|
routeData,
|
|
});
|
|
await NodeApp.writeResponse(response, res);
|
|
} else if (next) {
|
|
return next();
|
|
} else {
|
|
const response = await app.render(req);
|
|
await NodeApp.writeResponse(response, res);
|
|
}
|
|
};
|
|
}
|