Create a gist now

Instantly share code, notes, and snippets.

Sinatra server JSON file get requests mirroring directory structure
require 'sinatra/base'
require 'json'
require 'pathname'
FIXTURESDIR="fixtures"
class JSONFileServer < Sinatra::Base
#TODO: When request is not JSON return 406
# when request.accept.include?("application/json") #JSON requested
get '*' do
path = Pathname.new("#{File.dirname(__FILE__)}/#{FIXTURESDIR}#{params[:splat].first()}")
pathPlusJson = Pathname.new("#{path}.json")
if path.directory?
response = get_directory_contents_array(path.to_path)
return response.to_json
elsif pathPlusJson.exist? and pathPlusJson.file?
response = JSON.parse(IO.read(pathPlusJson.to_path))
return response.to_json
else
return create_response( {"error" => "Not Found" }.to_json, 404 )
end
end
post '*' do
path = Pathname.new("#{File.dirname(__FILE__)}/#{FIXTURESDIR}#{params[:splat].first()}")
if !File.exist?(path.dirname())
return create_response( {"error" => "Not Found" }.to_json, 404 )
end
filename = Pathname.new("#{path.to_path}.json")
if File.exist?(filename.to_path())
return create_response( {"error" => "Resource already exists" }.to_json, 409 )
end
body_data = JSON.parse(request.body.string)
write_hash_to_file_json(filename,body_data)
return 200
end
#Put doesn't currently do any actual updating, it simply stomps the contents of an existing
#resource with the same name as the one being put.
put '*' do
path = Pathname.new("#{File.dirname(__FILE__)}/#{FIXTURESDIR}#{params[:splat].first()}")
if !File.exist?(path.dirname())
return create_response( {"error" => "Not Found" }.to_json, 404 )
end
filename = Pathname.new("#{path.to_path}.json")
body_data = JSON.parse(request.body.string)
write_hash_to_file_json(filename,body_data)
return 200
end
delete '*' do
path = Pathname.new("#{File.dirname(__FILE__)}/#{FIXTURESDIR}#{params[:splat].first()}")
if !File.exist?(path.dirname())
return create_response( {"error" => "Not Found" }.to_json, 404 )
end
filename = Pathname.new("#{path.to_path}.json")
if !File.exist?(filename.to_path())
return create_response( {"error" => "Not Found" }.to_json, 404 )
end
FileUtils.rm(filename.to_path())
return 200
end
def get_directory_contents_array(path)
size = 0
if !path.end_with?("/")
path += "/"
end
path += "*"
files = Dir[path].select { |fpath| !File.directory? fpath }
if files.length == 0
return create_response( {"error" => "Not Found" }.to_json, 404 )
end
response = files.map { |file_name| JSON.parse(IO.read(file_name)) }
return response
end
def create_response(body,status)
response = Array.new(2)
response[0] = status
response[1] = body
return response
end
def write_hash_to_file_json(fullpath,contents)
IO.write(fullpath.to_path, contents.to_json, 0)
end
end
if __FILE__ == $0
JSONFileServer.run!
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment