# frozen_string_literal: true require "sinatra" require "puma" require 'route_downcaser' class RestServer < Sinatra::Base set :server, :puma enable :logging if ENV["debug"] == "true" set :bind, "0.0.0.0" use RouteDowncaser::DowncaseRouteMiddleware def has_id?(model, id) Entities.models[model].key?(id) end def not_have(id) [404, JSON.generate({ error: "'#{id}' not found" })] end get "/" do summary = { models: Entities.models.keys.to_s } summary[:db] = MongoClient.client.summary.to_s if ENV['mongodb'] JSON.generate(summary) rescue Exception => e [500, e.message] end Entities.models.each_key do |model| post "/#{model.downcase}" do id = SecureRandom.uuid data = JSON.parse(request.body.read) if ENV['mongodb'] MongoClient.insert(model, data, id) else Entities.models[model][id] = data end [201, id] end get "/#{model.downcase}" do puts request.path.downcase if ENV['mongodb'] if params == {} JSON.generate(MongoClient.get_all(model)) else [200, JSON.generate(MongoClient.find_all(model, params))] end else return [200, Entities.models[model].to_s] if params == {} Entities.models[model].values.find_all { |val| val[params.keys[0]] == params.values[0] } end rescue Exception => e [404, "Nothing found using #{params}. Only first param considered. #{e.message}"] end get "/#{model.downcase}/:id" do |id| puts request.path.downcase if ENV['mongodb'] results = MongoClient.find(model, id) return not_have(id) unless results.first JSON.generate(results.first) else return not_have(id) unless has_id?(model, id) JSON.generate(Entities.models[model][id]) end end put "/#{model.downcase}/:id" do |id| puts request.path.downcase data = JSON.parse(request.body.read) if ENV['mongodb'] results = MongoClient.find(model, id) return not_have(id) unless results.first MongoClient.update(model, id, data) else return not_have(id) unless has_id?(model, id) Entities.models[model][id] = data end 204 end delete "/#{model.downcase}/:id" do |id| puts request.path.downcase if ENV['mongodb'] results = MongoClient.find(model, id) return not_have(id) unless results.first MongoClient.delete(model, id) else return not_have(id) unless has_id?(model, id) Entities.models[model].delete(id) end 204 end end end