blob: 5bb104914daeaec82921fcfb3cbed963a2aff141 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
import type { NodeApp } from 'astro/app/node';
import { createAppHandler } from './serve-app.js';
import type { RequestHandler } from './types.js';
/**
* Creates a middleware that can be used with Express, Connect, etc.
*
* Similar to `createAppHandler` but can additionally be placed in the express
* chain as an error middleware.
*
* https://expressjs.com/en/guide/using-middleware.html#middleware.error-handling
*/
export default function createMiddleware(app: NodeApp): RequestHandler {
const handler = createAppHandler(app);
const logger = app.getAdapterLogger();
// using spread args because express trips up if the function's
// stringified body includes req, res, next, locals directly
return async (...args) => {
// assume normal invocation at first
const [req, res, next, locals] = args;
// short circuit if it is an error invocation
if (req instanceof Error) {
const error = req;
if (next) {
return next(error);
// biome-ignore lint/style/noUselessElse: <explanation>
} else {
throw error;
}
}
try {
await handler(req, res, next, locals);
} catch (err) {
logger.error(`Could not render ${req.url}`);
console.error(err);
if (!res.headersSent) {
// biome-ignore lint/style/noUnusedTemplateLiteral: <explanation>
res.writeHead(500, `Server error`);
res.end();
}
}
};
}
|