Skip to content

Instantly share code, notes, and snippets.

@zosiu
Created March 8, 2015 14:37
Show Gist options
  • Save zosiu/317772af2bd709c177be to your computer and use it in GitHub Desktop.
Save zosiu/317772af2bd709c177be to your computer and use it in GitHub Desktop.
Grape setup with logging & documentation
module MyApp
module V1
class API < Grape::API
version 'v1', using: :path
format :json
before do
header['Access-Control-Allow-Origin'] = '*'
header['Access-Control-Request-Method'] = '*'
@log_start_t = Time.now
fil = ActionDispatch::Http::ParameterFilter.new Rails.application.config.filter_parameters
Rails.logger.tagged('API') do |logger|
logger.info "Parameters: #{fil.filter params.to_hash.except('route_info')}"
end
end
after do
@log_end_t = Time.now
total_runtime = ((@log_end_t - @log_start_t) * 1000).round(1)
db_runtime = (ActiveRecord::RuntimeRegistry.sql_runtime || 0).round(1)
Rails.logger.tagged('API') do |logger|
logger.info "Completed in #{total_runtime}ms (ActiveRecord: #{db_runtime}ms)"
end
end
rescue_from ActiveRecord::RecordInvalid do |e|
error_response message: e.record.errors.to_a.uniq.join(', '), status: 400
end
rescue_from ActiveRecord::RecordNotFound do |_|
error_response message: 'Record not found!', status: 404
end
rescue_from Grape::Exceptions::ValidationErrors do |e|
error_response message: e.message, status: 400
end
rescue_from :all do |e|
Rails.logger.tagged('API') do |logger|
logger.info "error: #{e.message}"
end
message = Rails.env.production? ? 'server error' : e.message
error_response message: message, status: 500
end
add_swagger_documentation api_version: 'v1', mount_path: '/api-docs', hide_format: true
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment