1
0
Fork 0
backend/main.rb

61 lines
1.5 KiB
Ruby
Raw Normal View History

2023-02-04 23:43:57 +00:00
#!/usr/bin/env ruby
# frozen_string_literal: true
require 'connection_pool'
require 'pg'
require 'sinatra'
2023-02-05 02:44:16 +00:00
require 'sinatra/json'
2023-02-04 23:43:57 +00:00
$DB_POOL = ConnectionPool.new size: 5, timeout: 5 do
PG.connect(
host: 'pg.causa-arcana.com',
dbname: 'leqsikoni',
user: 'leqsikoni',
password: 'ggeucene3ou7mqh2upehhm52tfp5bkcj',
2023-02-05 01:18:22 +00:00
).tap do |conn|
conn.type_map_for_results = PG::BasicTypeMapForResults.new conn
end
2023-02-04 23:43:57 +00:00
end
2023-02-05 02:53:47 +00:00
before do
headers 'Access-Control-Allow-Origin' => '*'
end
2023-02-05 01:18:22 +00:00
get '/examples' do
2023-02-04 23:43:57 +00:00
$DB_POOL.with do |db_conn|
2023-02-05 01:25:23 +00:00
ids =
case params[:ids]
2023-02-05 02:44:16 +00:00
when Array then params[:ids]
when String then params[:ids].split(',')
2023-02-05 01:25:23 +00:00
else raise 'Invalid param "ids"'
2023-02-05 02:44:16 +00:00
end.map { |id| Integer id }
2023-02-05 01:18:22 +00:00
examples = db_conn.exec_params(
(
<<~SQL
SELECT
array_agg(foo.value ORDER BY foo.language_id DESC)::text[] AS values
FROM example_texts foo
INNER JOIN (
SELECT example_id, language_id, MIN(index) as min_index
FROM example_texts
WHERE
example_id = ANY($1)
AND
(language_id = 5 OR language_id = 2)
GROUP BY example_id, language_id
) bar
ON
foo.example_id = bar.example_id AND
foo.language_id = bar.language_id AND
foo.index = bar.min_index
GROUP BY foo.example_id
SQL
),
[PG::TextEncoder::Array.new.encode(ids)],
).map { |row| row['values'] }
2023-02-05 02:44:16 +00:00
json examples
2023-02-04 23:43:57 +00:00
end
end