Sha256: ffdf0f5587b9b67273ab0afecd29a7cf3562035c9cb76c9039b36d580114cecc

Contents?: true

Size: 1.66 KB

Versions: 1

Compression:

Stored size: 1.66 KB

Contents

# frozen_string_literal: true

require 'sinatra'
require 'docdsl'
require 'json'

# Hosts the House server locally
class HouseServer < Sinatra::Application
  register Sinatra::DocDsl
  set :port, HouseTest::PORT

  page do
    title 'House Server'
    header 'Testing environment for Web and API testing'
    introduction 'This has some a simple data model for CRUD of entities via API, UI and gem'
  end

  doc_endpoint '/docs'

  documentation 'Retrieve all houses' do
    response 'Description of all houses'
  end
  get '/houses' do
    HouseTest.descriptions.to_s
  end

  documentation 'Get particular house description'
  get '/houses/:id' do |id|
    house = HouseTest.get(id)
    if house
      [200, { 'Content-Type' => 'text/json' }, house.description.to_s]
    else
      [404, { 'Content-Type' => 'text/json' }, 'Not Found']
    end
  end

  patch '/houses/:id' do |id|
    begin
      query = JSON.parse(request.body.string)
      id = HouseTest.update(id, query.keys.first, query.values.first)
      JSON.generate(updated: id)
    rescue StandardError => e
      e.message
    end
  end

  documentation 'Create a new house'
  post '/houses' do
    begin
      house_id = if request.body.string.empty?
                   HouseTest.add
                 else
                   HouseTest.add(JSON.parse(request.body.string))
                 end
    rescue StandardError => e
      [200, { 'Content-Type' => 'text/json' }, e.message]
    else
      [200, { 'Content-Type' => 'text/json' }, house_id]
    end
  end

  documentation 'Nothing under /. Go look at /docs' do
    response 'redirects to the documentation page'
    status 303
  end
  get '/' do
    redirect '/docs'
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
house_test-0.1.1 lib/house_test/server/house_server.rb