Class: Userbin::Request::Middleware::JSONParser

Inherits:
Faraday::Response::Middleware
  • Object
show all
Defined in:
lib/userbin/request.rb

Instance Method Summary collapse

Instance Method Details

#on_complete(env) ⇒ Object



120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
# File 'lib/userbin/request.rb', line 120

def on_complete(env)
  response = if env[:body].nil? || env[:body].empty?
    {}
  else
    begin
      MultiJson.load(env[:body], :symbolize_keys => true)
    rescue MultiJson::LoadError
      raise Userbin::ApiError, 'Invalid response from Userbin API'
    end
  end

  case env[:status]
  when 200..299
    # OK
  when 400
    raise Userbin::BadRequestError, response[:message]
  when 401
    raise Userbin::UnauthorizedError, response[:message]
  when 403
    raise Userbin::ForbiddenError, response[:message]
  when 404
    raise Userbin::NotFoundError, response[:message]
  when 419
    # session token is invalid so clear it
    RequestStore.store[:userbin].session_token = nil

    raise Userbin::UserUnauthorizedError, response[:message]
  when 422
    raise Userbin::InvalidParametersError, response[:message]
  else
    raise Userbin::ApiError, response[:message]
  end

  env[:body] = {
    data: response,
    metadata: [],
    errors: {}
  }
end