| 1 | import * as Drizzle from "@/Drizzle/Postgres.ts"; |
| 2 | import * as Railway from "@/Railway"; |
| 3 | import * as Effect from "effect/Effect"; |
| 4 | import { HttpServerRequest } from "effect/http/HttpServerRequest"; |
| 5 | import * as HttpServerResponse from "effect/http/HttpServerResponse"; |
| 6 | import { Partition, Site } from "./suite-env.ts"; |
| 7 | import { Db } from "./postgres-shared.ts"; |
| 8 | |
| 9 | export { Db, Site }; |
| 10 | |
| 11 | export 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 | */ |
| 17 | export 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 | ) {} |