serveWebappDist

This commit is contained in:
Julien Valverdé
2025-09-13 01:37:48 +02:00
parent 5dba4eff03
commit 97b2803167

View File

@@ -1,5 +1,5 @@
import { HttpMiddleware, HttpRouter, HttpServer, HttpServerResponse, Path } from "@effect/platform" import { FileSystem, HttpMiddleware, HttpRouter, HttpServer, HttpServerRequest, HttpServerResponse, Path } from "@effect/platform"
import { Console, Effect, flow, Layer } from "effect" import { Duration, Effect, flow } from "effect"
const router = HttpRouter.empty.pipe( const router = HttpRouter.empty.pipe(
@@ -13,23 +13,38 @@ export const HttpAppDevelopment = router.pipe(
HttpServer.withLogAddress, HttpServer.withLogAddress,
) )
export const HttpAppProduction = Effect.Do.pipe(
Effect.bind("path", () => Path.Path), const serveWebappDist = Effect.fnUntraced(function*(file: string) {
Effect.bind("webappDist", ({ path }) => Effect.map( const path = yield* Path.Path
path.fromFileUrl(new URL(".", import.meta.resolve("@website/webapp"))), const fs = yield* FileSystem.FileSystem
v => path.join(v, "dist"), const source = path.join(
yield* path.fromFileUrl(new URL(".", import.meta.resolve("@website/webapp"))),
"dist", file,
)
const exists = yield* fs.stat(source).pipe(
Effect.andThen(stat => stat.type === "File"),
Effect.catchAll(() => Effect.succeed(false)),
)
return exists
? yield* HttpServerResponse.setHeader(
yield* HttpServerResponse.file(source),
"Cache-Control",
`public, max-age=${Duration.toSeconds("365 days")}, immutable`
)
: yield* HttpServerResponse.setStatus(HttpServerResponse.empty(), 404)
})
export const HttpAppProduction = router.pipe(
HttpRouter.all("/assets/*", Effect.andThen(
HttpServerRequest.HttpServerRequest,
req => serveWebappDist(req.url),
)), )),
HttpRouter.all("*", serveWebappDist("index.html")),
Effect.map(({ path, webappDist }) => router.pipe( HttpServer.serve(flow(
HttpRouter.all("/", HttpServerResponse.file(path.join(webappDist, "index.html"))), HttpMiddleware.logger,
HttpRouter.all("/assets", HttpServerResponse.file(path.join(webappDist, "assets"))), HttpMiddleware.xForwardedHeaders,
HttpServer.serve(flow(
HttpMiddleware.logger,
HttpMiddleware.xForwardedHeaders,
)),
HttpServer.withLogAddress,
)), )),
HttpServer.withLogAddress,
Layer.unwrapEffect,
) )