1import * as Drizzle from "@/Drizzle/Postgres.ts";
2import * as Railway from "@/Railway";
3import * as Effect from "effect/Effect";
4import { HttpServerRequest } from "effect/http/HttpServerRequest";
5import * as HttpServerResponse from "effect/http/HttpServerResponse";
6import { Partition, Site } from "./suite-env.ts";
7import { Db } from "./postgres-shared.ts";
8
9export { Db, Site };
10
11export const POSTGRES_PORT = 3000;
12
13/**
14 * HTTP Service that binds Postgres via {@link Railway.ConnectPostgres}
15 * and answers SELECT 1. Never returns the connection string.
16 */
17export default class PostgresApi extends Railway.Service<PostgresApi>()(
18 "PostgresApi",
19 {
20 project: Site,
21 environment: Partition,
22 main: import.meta.url,
23 port: POSTGRES_PORT,
24 build: { install: ["pg"] },
25 },
26 Effect.gen(function* () {
27 const conn = yield* Railway.ConnectPostgres(Db);
28 const db = yield* Drizzle.Postgres(conn.connectionString);
29
30 return {
31 fetch: Effect.gen(function* () {
32 const request = yield* HttpServerRequest;
33 const path = new URL(request.url, "http://service").pathname;
34 if (path === "/ping") {
35 return yield* HttpServerResponse.json({ ok: true });
36 }
37 const rows = yield* db.execute("select 1 as ok", "objects");
38 if (path === "/health" || path === "/") {
39 return yield* HttpServerResponse.json({ rows });
40 }
41 return yield* HttpServerResponse.json({ rows }, { status: 404 });
42 }).pipe(
43 Effect.catch((error) =>
44 HttpServerResponse.json(
45 { ok: false, error: String(error) },
46 { status: 500 },
47 ),
48 ),
49 ),
50 };
51 }).pipe(Effect.provide(Railway.ConnectPostgresHttp)),
52) {}