# frozen_string_literal: true module Api class UsersController < ApiController skip_before_action :verify_authenticity_token, only: [:index] # # Queries the database for a Steam UID, and returns the User's Discord ID if it exists # # @param uid [String] The Steam UID to query # def index users = [] if (steam_uids_string = params[:steam_uids]) users += find_users_by_steam_uid(steam_uids_string) end if (discord_ids_string = params[:discord_ids]) users += find_users_by_discord_id(discord_ids_string) end render json: users rescue => e render_too_big!(e.message) end # # Returns a user's steam_uid based on their discord ID # # @param discord_id [String] The Discord ID to query # def show discord_id = params[:discord_id] user = User.find_by_discord_id(discord_id) render json: {discord_id: user&.discord_id || discord_id, steam_uid: user&.steam_uid} end private def render_too_big!(label) # Lol render json: {error: "Exceeded max size of 100 entries for #{label}"}, status: 413 end def find_users_by_steam_uid(steam_uids) steam_uids = json_array(steam_uids) if steam_uids.is_a?(String) raise "steam_uids" if steam_uids.size > 100 # No n+1 queries here! users = User.where(steam_uid: steam_uids).pluck(:steam_uid, :discord_id).to_h # This is formatted so if the provided steam_uid doesn't match, it'll still have an entry in the results steam_uids.map { |steam_uid| {discord_id: users[steam_uid], steam_uid: steam_uid} } end def find_users_by_discord_id(discord_ids) discord_ids = json_array(discord_ids) if discord_ids.is_a?(String) raise "discord_ids" if discord_ids.size > 100 # No n+1 queries here! users = User.where(discord_id: discord_ids).pluck(:discord_id, :steam_uid).to_h # This is formatted so if the provided discord_id doesn't match, it'll still have an entry in the results discord_ids.map { |discord_id| {discord_id: discord_id, steam_uid: users[discord_id]} } end def json_array(string_input) JSON.parse(string_input) rescue [] end end end