require "http/client" require "http/headers" require "http/request" require "ishi/html" require "json" class Handler def query(sql) params = URI::Params.encode({"q": sql}) response = HTTP::Client.get URI.new( "http", "10.61.0.1", 4001, "/db/query", params) # This API only has a values key when there are actual results results = JSON.parse(response.body)["results"][0].as_h if results.has_key?("values") return results["values"].as_a.map { |r| [r[0].as_i, r[1].as_i] } end # Return a dummy result [[1922, 0]] end nombres = [] of String def normalize_name(s) # Remove diacritics, turn lowercase normalized = s.unicode_normalize(:nfkd).chars normalized.reject! { |c| !c.ascii_letter? }.join("").downcase end def run(request : HTTP::Request) unless (body = request.body).nil? query = JSON.parse(body) nombres = query["i"].as_s.split(",").map { |n| n.strip } nombres.reject! { |n| n.size == 0 } end if nombres.nil? || nombres.empty? nombres = ["maria", "juan"] end # Remove all diacritics and whatnot nombres = nombres.map { |n| normalize_name n } puts "Processing #{nombres}" buffer = IO::Memory.new Ishi.new(buffer) do canvas_size(800, 300) show_key(true) xrange(1922..2015) nombres.map { |nombre| sql = "SELECT anio, contador FROM nombres WHERE nombre = '#{nombre}' ORDER BY anio" x = Array(Int32).new y = Array(Int32).new query(sql).map { |r| x << r[0] y << r[1] } plot(x, y, title: nombre.titleize, style: :lines, linewidth: 3) } end # This is a whole page, we just need some bits html = buffer.to_s.split("\n") html = html[html.index("")] html = html.join("\n") + %(
Sorry, your browser seems not to support the HTML 5 canvas element
) { body: html, status_code: 200, headers: HTTP::Headers{"Content-Type" => "text/html"}, } end end