# frozen_string_literal: true require "sinatra" require "puma" class RestServer < Sinatra::Base set :server, :puma enable :logging if ENV["debug"] == "true" set :bind, "0.0.0.0" def has_id?(model, id) Entities.models[model].key?(id) end def not_found(id) [404, JSON.generate({ error: "'#{id}' not found" })] end get "/" do JSON.generate({ models: Entities.models.keys.to_s }) end Entities.models.each_key do |model| post "/#{model}" do id = SecureRandom.uuid Entities.models[model][id] = JSON.parse(request.body.read) [201, id] end get "/#{model}" do puts params puts params.class puts params == {} return [200, Entities.models[model].to_s] if params == {} Entities.models[model].values.find_all { |val| val[params.keys[0]] == params.values[0] } rescue Exception [404, "Nothing found using #{params}. Only first param considered"] end get "/#{model}/:id" do |id| return not_found(id) unless has_id?(model, id) JSON.generate(Entities.models[model][id]) end put "/#{model}/:id" do |id| return not_found(id) unless has_id?(model, id) Entities.models[model][id] = JSON.parse(request.body.read) 204 end delete "/#{model}/:id" do |id| return not_found(id) unless has_id?(model, id) Entities.models[model].delete(id) 204 end end end