summaryrefslogtreecommitdiff
path: root/lib/chef_zero/endpoints/rest_list_endpoint.rb
blob: 135f0e96f2893ec4dbda29ff33735b4236df9644 (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
require "ffi_yajl"
require "chef_zero/rest_base"

module ChefZero
  module Endpoints
    # Typical REST list endpoint (/roles or /data/BAG)
    class RestListEndpoint < RestBase
      def initialize(server, identity_keys = [ "name" ])
        super(server)
        identity_keys = [ identity_keys ] if identity_keys.is_a?(String)
        @identity_keys = identity_keys
      end

      attr_reader :identity_keys

      def get(request)
        # Get the result
        result_hash = {}
        list_data(request).sort.each do |name|
          result_hash[name] = (build_uri(request.base_uri, request.rest_path + [name])).to_s
        end
        json_response(200, result_hash)
      end

      def post(request)
        contents = request.body
        key = get_key(contents)
        if key.nil?
          error(400, "Must specify #{identity_keys.map { |k| k.inspect }.join(' or ')} in JSON")
        else
          create_data(request, request.rest_path, key, contents)
          json_response(201, { "uri" => (build_uri(request.base_uri, request.rest_path + [key])).to_s })
        end
      end

      def get_key(contents)
        json = FFI_Yajl::Parser.parse(contents)
        identity_keys.map { |k| json[k] }.select { |v| v }.first
      end
    end
  end
end