Kjson

Usage

require 'roda'

class App < Roda
  route do |r|
    r.plugin :kjson

    r.api do
      r.endpoint "user" do
        r.endpoint "new" do
          r.success {"name": "Emmy"}
        end
      end
    end
  end
end

run App.freeze.new

Create a successful response

r.api do
  r.success
end

An alternative way is,

class AlwaysSuccessService
  def call
    throw :success
  end
end

r.api do
  r.endpoint "always_success" do
    service = AlwaysSuccessService.new
    service.()
  end
end

It will generate,

{
  "data": null
  "error": null
}

Fill data in response

r.api do
  r.success data
end

Or,

r.api do
  throw :success, data
end

A complex endpoint

For request "endpoint":"part.value","data":null,

r.api do
  r.endpoint "part" do
    puts r.endpoint # "value"
  end
end

An arbitrary exception

r.api do
  raise "Something went wrong."
end

Response will look as:

{
  "data": null,
  "error": {
    "type": "SERVICE_ERROR",
    "message": "INTERNAL",
    "cause": {
      "message": "Something went wrong."
    }
  }
}

A service exception

r.api do
  throw :error, "RESOURCE_EXHAUSTED"
end

Response will look as:

{
  "data": null,
  "error": {
    "type": "SERVICE_ERROR",
    "message": "RESOURCE_EXHAUSTED"
  }
}