You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
97 lines
1.7 KiB
TypeScript
97 lines
1.7 KiB
TypeScript
import { serve } from "./deps/std.ts";
|
|
import {
|
|
HTTPHandler,
|
|
catching,
|
|
compressResponse,
|
|
filter,
|
|
log,
|
|
orElse,
|
|
routePaths,
|
|
setHeaders,
|
|
staticString,
|
|
} from "./deps/shirt.ts";
|
|
import { serveApi } from "./api.ts";
|
|
|
|
import { styleText, bundleText, mode } from "../build/mod.ts";
|
|
|
|
const apiHandler = filter(
|
|
(req) => new URL(req.url).pathname.split("/")[1] === "api",
|
|
setHeaders([["content-type", "application/json"]], serveApi),
|
|
);
|
|
|
|
const notFound = (_req: Request) => {
|
|
return new Response("Not found", { status: 404 });
|
|
};
|
|
|
|
const internalServerError = (_req: Request, e: unknown) => {
|
|
console.error(e);
|
|
|
|
return new Response("Something went wrong", { status: 500 });
|
|
};
|
|
|
|
const renderHeadResourceLinks = () => {
|
|
if (mode === "dev") {
|
|
return `
|
|
<script src="/app.js"></script>
|
|
<link rel="stylesheet" href="/app.css">
|
|
`;
|
|
}
|
|
|
|
return `
|
|
<style>${styleText}</style>
|
|
<script>${bundleText}</script>
|
|
`;
|
|
};
|
|
|
|
const BODY = `
|
|
<!DOCTYPE html>
|
|
<html>
|
|
<head>
|
|
<title>zchema</title>
|
|
${renderHeadResourceLinks()}
|
|
</head>
|
|
<body>
|
|
<noscript>You must enable JavaScript</noscript>
|
|
</body>
|
|
</html>
|
|
`;
|
|
|
|
const serveRoot = staticString(BODY, "text/html");
|
|
|
|
const serveDevResources = filter(
|
|
(_req) => mode === "dev",
|
|
routePaths({
|
|
"/app.js": staticString(bundleText, "text/javascript"),
|
|
"/app.css": staticString(styleText, "text/css"),
|
|
}),
|
|
);
|
|
|
|
const handle = log(
|
|
compressResponse(
|
|
catching(
|
|
orElse(
|
|
apiHandler,
|
|
orElse(serveDevResources, orElse(serveRoot, notFound)),
|
|
),
|
|
internalServerError,
|
|
),
|
|
),
|
|
);
|
|
|
|
const handle_ = async (req: Request) => {
|
|
const res = await handle(req);
|
|
|
|
return res;
|
|
};
|
|
|
|
serve(handle_, {
|
|
port: 8998,
|
|
onError: (e) => {
|
|
console.debug(e);
|
|
|
|
return new Response("An internal error has occurred", {
|
|
status: 500,
|
|
});
|
|
},
|
|
});
|