2022-06-06 16:49:53 +00:00
|
|
|
import { polyfill } from '@astrojs/webapi';
|
2022-03-24 11:26:25 +00:00
|
|
|
import type { SSRManifest } from 'astro';
|
2022-06-06 16:49:53 +00:00
|
|
|
import { NodeApp } from 'astro/app/node';
|
2022-03-24 11:26:25 +00:00
|
|
|
import type { IncomingMessage, ServerResponse } from 'http';
|
2022-03-24 21:08:36 +00:00
|
|
|
import type { Readable } from 'stream';
|
2022-03-24 11:26:25 +00:00
|
|
|
|
|
|
|
polyfill(globalThis, {
|
2022-03-24 11:27:15 +00:00
|
|
|
exclude: 'window document',
|
2022-03-24 11:26:25 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
export function createExports(manifest: SSRManifest) {
|
2022-03-24 21:08:36 +00:00
|
|
|
const app = new NodeApp(manifest);
|
2022-03-24 11:26:25 +00:00
|
|
|
return {
|
|
|
|
async handler(req: IncomingMessage, res: ServerResponse, next?: (err?: unknown) => void) {
|
2022-07-22 19:22:31 +00:00
|
|
|
try {
|
|
|
|
const route = app.match(req);
|
2022-03-24 11:26:25 +00:00
|
|
|
|
2022-07-22 19:22:31 +00:00
|
|
|
if (route) {
|
|
|
|
try {
|
|
|
|
const response = await app.render(req);
|
|
|
|
await writeWebResponse(res, response);
|
|
|
|
} catch (err: unknown) {
|
|
|
|
if (next) {
|
|
|
|
next(err);
|
|
|
|
} else {
|
|
|
|
throw err;
|
|
|
|
}
|
2022-03-24 11:26:25 +00:00
|
|
|
}
|
2022-07-22 19:22:31 +00:00
|
|
|
} else if (next) {
|
|
|
|
return next();
|
|
|
|
}
|
|
|
|
} catch(err: unknown) {
|
|
|
|
if(!res.headersSent) {
|
|
|
|
res.writeHead(500, `Server error`);
|
|
|
|
res.end();
|
2022-03-24 11:26:25 +00:00
|
|
|
}
|
|
|
|
}
|
2022-03-24 11:27:15 +00:00
|
|
|
},
|
|
|
|
};
|
2022-03-24 11:26:25 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
async function writeWebResponse(res: ServerResponse, webResponse: Response) {
|
|
|
|
const { status, headers, body } = webResponse;
|
|
|
|
res.writeHead(status, Object.fromEntries(headers.entries()));
|
|
|
|
if (body) {
|
2022-03-24 21:09:40 +00:00
|
|
|
for await (const chunk of body as unknown as Readable) {
|
2022-03-24 21:08:36 +00:00
|
|
|
res.write(chunk);
|
2022-03-24 11:26:25 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
res.end();
|
|
|
|
}
|