2022-03-24 11:26:25 +00:00
|
|
|
import type { SSRManifest } from 'astro';
|
|
|
|
import type { IncomingMessage, ServerResponse } from 'http';
|
|
|
|
import { NodeApp } from 'astro/app/node';
|
|
|
|
import { polyfill } from '@astrojs/webapi';
|
|
|
|
|
|
|
|
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) {
|
|
|
|
const app = new NodeApp(manifest, new URL(import.meta.url));
|
|
|
|
return {
|
|
|
|
async handler(req: IncomingMessage, res: ServerResponse, next?: (err?: unknown) => void) {
|
|
|
|
const route = app.match(req);
|
|
|
|
|
2022-03-24 11:27:15 +00:00
|
|
|
if (route) {
|
2022-03-24 11:26:25 +00:00
|
|
|
try {
|
|
|
|
const response = await app.render(req);
|
|
|
|
await writeWebResponse(res, response);
|
2022-03-24 11:27:15 +00:00
|
|
|
} catch (err: unknown) {
|
|
|
|
if (next) {
|
2022-03-24 11:26:25 +00:00
|
|
|
next(err);
|
|
|
|
} else {
|
|
|
|
throw err;
|
|
|
|
}
|
|
|
|
}
|
2022-03-24 11:27:15 +00:00
|
|
|
} else if (next) {
|
2022-03-24 11:26:25 +00:00
|
|
|
return next();
|
|
|
|
}
|
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) {
|
|
|
|
const reader = body.getReader();
|
|
|
|
while (true) {
|
|
|
|
const { done, value } = await reader.read();
|
|
|
|
if (done) break;
|
|
|
|
if (value) {
|
|
|
|
res.write(value);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
res.end();
|
|
|
|
}
|