Functions/historico/funko.cr

62 lines
1.6 KiB
Crystal
Raw Normal View History

require "json"
require "kemal"
require "pg"
require "pool/connection"
# get credentials from secrets
USER = File.read("/secrets/user").strip
PASS = File.read("/secrets/pass").strip
DBHOST = File.read("/secrets/dbhost").strip
DBURL = "postgres://#{USER}:#{PASS}@#{DBHOST}:5432/nombres"
puts "Connnecting to #{DBURL}"
# Connect to the database and get information about
# the requested names
get "/" do |env|
# Names are query parameters
# Split by commas, capitalize and take the first 5
names = env.params.query["names"]
.split(",").map(&.strip.capitalize)[..4]
# Prepare results table
results = [] of Array(String)
results << ["Año"] + names
(1922..2015).each do |anio|
results << [anio.to_s]
end
# Connect using credentials provided
2024-08-21 21:18:35 +00:00
db = DB.open DBURL
# Get the information for each name
names.map do |name|
# Normalize: remove diacritics etc.
name = name.unicode_normalize(:nfkd)
.chars.reject! { |character|
!character.ascii_letter? && (character != ' ')
}.join("").downcase
counter_per_year = {} of Int32 => Int32
2024-08-21 21:18:35 +00:00
db.query("
SELECT anio::integer, contador::integer
FROM nombres WHERE nombre = $1", name) do |result_set|
result_set.each do
counter_per_year[result_set.read(Int32)] = result_set.read(Int32)
end
end
(1922..2015).each do |anio|
results[anio - 1921] << counter_per_year.fetch(anio, 0).to_s
end
end
results.to_json
2024-08-21 21:18:35 +00:00
ensure
db.try &.close
end
get "/ping/" do
2024-08-21 21:18:35 +00:00
db = DB.open DBURL
db.exec("SELECT 42")
"OK"
2024-08-21 21:18:35 +00:00
ensure
db.try &.close
end