Sha256: 33f624ddd171c6f16586b73088644b2641fee9c905042b08bf5f13de97038175
Contents?: true
Size: 1.81 KB
Versions: 1
Compression:
Stored size: 1.81 KB
Contents
# 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_found(id) [404, JSON.generate({ error: "'#{id}' not found" })] end get "/" do JSON.generate({ models: Entities.models.keys.to_s }) end # get '*' do # Could do something like following to make case insensitive. Need all 1 method logic to be in 1 place # file_path = File.join(File.dirname(__FILE__), 'public', request.path.downcase) # File.exist?(file_path) ? send_file(file_path) : halt 404 # end Entities.models.each_key do |model| post "/#{model.downcase}" do id = SecureRandom.uuid Entities.models[model][id] = JSON.parse(request.body.read) [201, id] end get "/#{model.downcase}" do puts request.path.downcase 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.downcase}/:id" do |id| return not_found(id) unless has_id?(model, id) JSON.generate(Entities.models[model][id]) end put "/#{model.downcase}/: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.downcase}/:id" do |id| return not_found(id) unless has_id?(model, id) Entities.models[model].delete(id) 204 end end end
Version data entries
1 entries across 1 versions & 1 rubygems
Version | Path |
---|---|
schemaless_rest_api-0.1.1 | lib/schemaless_rest_api/rest_server.rb |