glats/handler

Request handler will handle receiving messages from a subscription, pass the data to a callback and then reply to NATS with the returned data.

Example

import gleam/option.{None}
import gleam/result
import gleam/erlang/process
import glats
import glats/handler.{Reply, Request, Response}

pub fn main() {
  use conn <- result.then(glats.connect("localhost", 4222, []))

  // Start a request handler actor that will call `ping_pong_handler` for
  // every request received from NATS topic "do.ping".
  assert Ok(_actor) =
    handler.handle_request(conn, [], "do.ping", None, ping_pong_handler)

  process.sleep_forever()

  Ok(Nil)
}

pub fn ping_pong_handler(req: Request, state) {
  // Got message: Hello
  io.println("Got message: " <> req.body)

  // Reply with a message with the same headers and append to body.
  Reply(
    Response(
      headers: req.headers,
      reply_to: None,
      body: req.body <> " from glats!",
    ),
    state,
  )
}

Then in a shell with natscli.

$ nats req do.ping 'Hello'
12:16:47 Sending request on "do.ping"
12:16:47 Received with rtt 427.64µs
Hello from glats!

Types

The message data received from the request handler’s topic.

pub type Request {
  Request(headers: dict.Dict(String, String), body: String)
}

Constructors

  • Request(headers: dict.Dict(String, String), body: String)

The request handling callback that should be passed to the request handler. This will be called for every request received.

pub type RequestHandler(a) =
  fn(Request, a) -> RequestOutcome(a)

Next step for the request handler to do.

pub type RequestOutcome(a) {
  Reply(response: Response, state: a)
  Stop(process.ExitReason)
}

Constructors

  • Reply(response: Response, state: a)

    The request handler will reply to the requester with the response and save the state.

  • Stop(process.ExitReason)

    The request handler will stop with provided exit reason.

The message data that should be replied to the requester.

pub type Response {
  Response(
    headers: dict.Dict(String, String),
    reply_to: option.Option(String),
    body: String,
  )
}

Constructors

  • Response(
      headers: dict.Dict(String, String),
      reply_to: option.Option(String),
      body: String,
    )

Functions

pub fn handle_request(
  conn: Subject(ConnectionMessage),
  state: a,
  topic: String,
  opts: List(SubscribeOption),
  handler: fn(Request, a) -> RequestOutcome(a),
) -> Result(Subject(SubscriptionMessage), StartError)

Starts an actor that subscribes to the desired NATS topic and calls the provided request handler with the request data and replies to NATS with the returned message data from the request handler.

Search Document