Effect CommunityEC
Effect Community12mo ago
40 replies
kristo

How to start `HttpServer`

The Http docs all reference starting a server using Layer.launch, but I want to start my server among a set of other services I am running, so within an effect.

It looks like HttpApiBuilder.serve returns a
Layer
. How should I get access to an effect so I can

const main = Effect.gen(function* () {
  yield* Effect.log("Starting Server...")
  const { run } = yield* SomeBackgroundService
  yield* run.pipe(Effect.fork)

  const server = ???
  yield* server.start()
})


My server code:
// Define our API with one group named "Health"
const ServerApi = HttpApi.make("ServerApi").add(
  HttpApiGroup.make("Health")
    .add(HttpApiEndpoint.get("hello-world")`/`.addSuccess(Schema.String))
    .add(
      HttpApiEndpoint.get("health-check")`/health-check`.addSuccess(
        Schema.String,
      ),
    ),
)

// Implement the "Health" group
const HealthLive = HttpApiBuilder.group(ServerApi, "Health", (handlers) => {
  return handlers
    .handle("hello-world", () => Effect.succeed("Hello, World!"))
    .handle("health-check", () => Effect.succeed("Looks ok."))
})

// Provide the implementation for the API
export const ServerApiLive = HttpApiBuilder.api(ServerApi).pipe(
  Layer.provide(HealthLive),
  HttpServer.withLogAddress,
  Layer.provide(BunHttpServer.layer({})),
)
Was this page helpful?