Effect CommunityEC
Effect Community5mo ago
4 replies
Chan Nyein Thaw

How do I catch SocketError in Websocket, HttpRouter.

Is there a way to catch SocketError especially for disconnection. Here is the playground link: https://effect.website/play#3af7932a6ce2.

Here's the code
import { NodeContext, NodeHttpServer, NodeRuntime } from "@effect/platform-node"

import {
  HttpRouter,
  HttpServer,
  HttpServerRequest,
  HttpServerResponse,
} from '@effect/platform'
import { Effect, Layer, Logger, LogLevel } from 'effect'
import { createServer } from "node:http"

const port = 3001
const mainLayer = Layer.empty.pipe(Layer.merge(NodeContext.layer))

const ws = HttpRouter.get(
  '/',
  Effect.gen(function* () {
    const request = yield* HttpServerRequest.HttpServerRequest
    if (request.headers.upgrade === 'websocket') {
      const socket = yield* HttpServerRequest.upgrade

      yield* socket.run((chunk) => {
        const text = new TextDecoder().decode(chunk)

        return Effect.log(text)
      })

      return yield* HttpServerResponse.empty()
    }

    return HttpServerResponse.html(
      `<script>new WebSocket("ws://localhost:3001").addEventListener('open', (e) => e.target.send("Hello from client!"));</script>`,
    )
  }),
)

const router = HttpRouter.empty.pipe(ws)
const app = router.pipe(HttpServer.serve(), HttpServer.withLogAddress)

app.pipe(
  Layer.provide(
    NodeHttpServer.layer(() => createServer(), { port })
  ),
  Layer.launch,
  Effect.provide(mainLayer),
  Logger.withMinimumLogLevel(
    process.env.NODE_ENV === 'production' ? LogLevel.Info : LogLevel.Debug,
  ),
  NodeRuntime.runMain({
    disablePrettyLogger: process.env.NODE_ENV === 'production',
  }),
)
Effect Documentation
Was this page helpful?