-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
server.mjs
71 lines (60 loc) · 1.68 KB
/
server.mjs
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import { createServer } from 'http';
import { deserializeManifestData, matchRoute } from 'astro/routing';
import { createResult } from 'astro/ssr/result.js';
import { renderPage } from 'astro/server/index.js';
import reactRenderer from '@astrojs/renderer-react';
import reactServerRenderer from '@astrojs/renderer-react/server.js';
import fs from 'fs';
const renderers = [
Object.create(reactRenderer, {
ssr: {
value: reactServerRenderer
}
})
];
const serverRoot = new URL('../dist/server/', import.meta.url);
const manifestData = JSON.parse(await fs.promises.readFile(new URL('./manifest.json', serverRoot)));
const manifest = deserializeManifestData(manifestData);
async function handle(req, res) {
const route = matchRoute(req.url, manifest);
if(route) {
const modFile = new URL('./' + route.distEntry, serverRoot);
const mod = await import(modFile);
const { default: Component } = mod;
// TODO get params
const result = createResult({
astroConfig: {
buildOptions: {}
},
logging: {},
origin: 'http:https://example.com',
params: {},
pathname: req.url,
renderers,
links: undefined, // TODO
scripts: undefined // TODO
});
const pageProps = {};
let html = await renderPage(result, Component, pageProps, null);
res.writeHead(200, {
'Content-Type': 'text/html'
});
res.end(html)
} else {
res.writeHead(404);
res.end();
}
}
const server = createServer((req, res) => {
handle(req, res).catch(err => {
console.error(err);
res.writeHead(500, {
'Content-Type': 'text/plain'
});
res.end(err.toString());
})
});
server.listen(8080);
console.log('Serving at http:https://localhost:8080');
// Silence weird <time> warning
console.error = () => {};