astro/examples/ssr/server/server.mjs
Matthew Phillips 5e52814d97
Adapters v0 (#2855)
* Adapter v0

* Finalizing adapters

* Update the lockfile

* Add the default adapter after config setup is called

* Create the default adapter in config:done

* Fix lint error

* Remove unused callConfigSetup

* remove unused export

* Use a test adapter to test SSR

* Adds a changeset

* Updated based on feedback

* Updated the lockfile

* Only throw if set to a different adapter

* Clean up outdated comments

* Move the adapter to an  config option

* Make adapter optional

* Update the docs/changeset to reflect config API change

* Clarify regular Node usage
2022-03-24 07:26:25 -04:00

45 lines
1 KiB
JavaScript

import { createServer } from 'http';
import fs from 'fs';
import mime from 'mime';
import { apiHandler } from './api.mjs';
import { handler as ssrHandler } from '../dist/server/entry.mjs';
const clientRoot = new URL('../dist/client/', import.meta.url);
async function handle(req, res) {
ssrHandler(req, res, async () => {
// Did not match an SSR route
if (/^\/api\//.test(req.url)) {
return apiHandler(req, res);
} else {
let local = new URL('.' + req.url, clientRoot);
try {
const data = await fs.promises.readFile(local);
res.writeHead(200, {
'Content-Type': mime.getType(req.url),
});
res.end(data);
} catch {
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(8085);
console.log('Serving at http://localhost:8085');
// Silence weird <time> warning
console.error = () => {};