From Rails to KrakenD proxy: config generation for your routes

require "action_dispatch/routing/inspector"

begin
  namespace :krakend do
    task :routes => :environment do

      inspector = ActionDispatch::Routing::RoutesInspector.new(Rails.application.routes.routes)
      formatter = CustomRoutesFormatter.new
      routes_filter = {}

      puts inspector.format(formatter, routes_filter)
    end
  end
end

class CustomRoutesFormatter < ActionDispatch::Routing::ConsoleFormatter::Expanded
  def section_title(title)
  end

  def section(routes)
    @buffer << draw_expanded_section(routes)
  end

  private

  def draw_expanded_section(routes)
    routes.map.each_with_index do |r, i|
      path = r[:path].gsub("(.:format)", "").gsub(/:([a-z_]*)/, "{\\1}")

      <<~MESSAGE.chomp
        {
          "endpoint": "#{path}",
          "method": "#{r[:verb]}",
          "querystring_params": ["*"],
          "extra_config": {},
          "output_encoding": "no-op",
          "concurrent_calls": 1,
          "headers_to_pass": ["*"],
          "backend": [
            {
              "url_pattern": "#{path}",
              "encoding": "no-op",
              "extra_config": {},
              "sd": "static",
              "host": [
                "http://rails-app"
              ],
              "disable_host_sanitize": true
            }
          ]
        },
      MESSAGE
    end
  end
end

This approach can help you easily build krakend.json for your rails application.

401 with devise token based auth

Recently I had a problem with token based authentication, when we switched in our cluster for two pods for our rails-based application we had a 401 response for each second request.

So the problem was fixed with defining a secret key in devise config, it was very simple fix, but I spent a lot of time for looking a solution :(, because I thought that the problem is caused by sessions or some session data.

Why the problem have appeared?

Secret key in devise is used for generating your application token string and second part of token – body. So when you have two instances of the same application without defining your secret key you will have different results on checking your token.

You may check this by trying this line in your application console with different secret key.