Effect CommunityEC
Effect Community3y ago
5 replies
jasonkuhrt

Request for Feedback on Custom Keypress Handling

Cans someone give me feedback on this code.

I want to perform some custom handling of keypresses coming into the process, but not block regular behaviour of sigterm etc. My general approach right now is looking like as follows.

export const stream = (params?: { exitOnCtrlC?: boolean }) =>
  pipe(
    Stream.repeatEffect(awaitKeyPress),
    Stream.map((event) =>
      event.name == `c` && event.ctrl == true && params?.exitOnCtrlC !== false ? Exit.unit : event,
    ),
    Stream.takeUntil(Exit.isExit),
  )

import { KeyPress } from './src/lib/KeyPress/index.js'
import { Console, Effect, Exit, Option, pipe, Stream } from 'effect'

// prettier-ignore
const result = await pipe(
  KeyPress.stream(),
  Stream.tap(Console.log),
  Stream.runLast,
  Effect.runPromise,
)

if (Option.isSome(result)) {
  if (Exit.isExit(result.value)) {
    if (Exit.isSuccess(result.value)) {
      process.exit()
    } else {
      process.exit(1)
    }
  }
}

setTimeout(() => {
  console.log(`this should never happen`)
}, 1000)


This program works as I expected so far, however, I really can't tell if I'm using Effect optimally. WDYT?
Was this page helpful?