summaryrefslogtreecommitdiff
path: root/lib/nickserver/couch_db/response.rb
blob: eae5cc1f1a95f023639426e9b4b3cfef382fff9d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
require 'nickserver/couch_db'
require 'json'

module Nickserver::CouchDB
  class Response
    def initialize(nick, couch_response = {})
      @nick = nick
      @couch_status = couch_response[:status]
      @json = JSON.load(couch_response[:body]) if couch_status == 200
    end

    def status
      if ok? && empty? then 404
      else couch_status
      end
    end

    def content
      if ok? && !empty?
        key_response
      else
        not_found_response
      end
    end

    protected

    def key_response
      format address: nick.to_s, openpgp: key
    end

    def not_found_response
      format({})
    end

    def format(response)
      response.to_json
    end

    def key
      rows.first['value']
    end

    def ok?
      couch_status == 200
    end

    def empty?
      rows.empty?
    end

    def rows
      json['rows']
    end

    attr_reader :couch_status, :json, :nick
  end
end