Class: Npolar::Api::Client::NpolarApiCommand

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/npolar/api/client/npolar_api_command.rb

Constant Summary collapse

CMD =
"npolar-api"
PARAM =
{ method: "GET",
headers: false,
header: [],
level: Logger::WARN,
join: false,
uri: JsonApiClient::BASE }

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(argv = ARGV, param = PARAM) ⇒ NpolarApiCommand

Returns a new instance of NpolarApiCommand.



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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# File 'lib/npolar/api/client/npolar_api_command.rb', line 29

def initialize(argv=ARGV, param = PARAM)
  @param = param

  option_parser = OptionParser.new(argv) do |opts|
  
  opts.version = Npolar::Api::Client::VERSION
  
  opts.banner = "#{CMD} [options] [#{PARAM[:uri]}]/endpoint

#{CMD} /schema
#{CMD} -XPOST /endpoint --data=/file.json
#{CMD} -XPOST /endpoint --data='{\"title\":\"Title\"}'
#{CMD} -XPUT --headers http://admin:password@localhost:5984/testdb
#{CMD} -XPUT -iv -XPUT /endpoint/id -d@/path/to/id
cat id-1.json | #{CMD} -XPUT -iv -XPUT /endpoint/id-1 -d@-
#{CMD} -XDELETE /endpoint/id-1

#{CMD} is built on top of Typhoeus/libcurl.
For more information and source: https://github.com/npolar/npolar-api-ruby-client

Options:\n"

    opts.on("--auth", "Force authorization") do |auth|
      @param[:auth] = true
    end
  
    opts.on("--data", "-d=data", "Data (request body) for POST and PUT") do |data|
      if /^([@])?-$/ =~ data
        data = ARGF.read
      else
        if /^[@]/ =~ data
          data = data.gsub(/^[@]/, "")
        end
        if File.exists? data
          data = File.read data
        end
      end
      @data = data
      # Change default method to POST on --data
      if param[:method] == "GET"
        param[:method]="POST"
      end
    end

    opts.on("--debug", "Debug (alias for --level=debug") do
      @param[:level] = Logger::DEBUG
    end

    opts.on("--level", "-l=level", "Log level") do |level|
      @param[:level] = self.class.level(level)
    end

    opts.on("--method", "-X=method", "HTTP method, GET is default") do |method|
      param[:method] = method
    end

    opts.on("--header", "-H=header", "Add HTTP request header") do |header|
      param[:header] << header
    end

    opts.on("--ids=ids", "URI that returns identifiers") do |ids|
      @param[:ids] = ids
    end

    opts.on("--join", "Use --join with --ids to join documents into a JSON array") do |join|
      @param[:join] = true
    end

    opts.on("--concurrency", "-c=number", "Concurrency (max)") do |c|
      param[:concurrency] = c
    end

    opts.on("--slice", "-s=number", "Slice size on POST ") do |slice|
      param[:slice] = slice
    end

    opts.on("--headers", "-i", "Show HTTP response headers") do
      param[:headers] = true
    end

    opts.on("--verbose", "-v", "Verbose") do
      Typhoeus::Config.verbose = true
    end

  end
  
  option_parser.parse!

  # URI is first argument
  @uri = ARGV[0]
  if uri.nil?
    puts option_parser.help
    exit(1)
  end
  
  @log = Logger.new(STDERR)
  @log.level = param[:level]
end

Instance Attribute Details

#clientObject

Returns the value of attribute client.



27
28
29
# File 'lib/npolar/api/client/npolar_api_command.rb', line 27

def client
  @client
end

#dataObject

Returns the value of attribute data.



27
28
29
# File 'lib/npolar/api/client/npolar_api_command.rb', line 27

def data
  @data
end

#hostObject

Returns the value of attribute host.



27
28
29
# File 'lib/npolar/api/client/npolar_api_command.rb', line 27

def host
  @host
end

#logObject

Returns the value of attribute log.



27
28
29
# File 'lib/npolar/api/client/npolar_api_command.rb', line 27

def log
  @log
end

#paramObject

Returns the value of attribute param.



27
28
29
# File 'lib/npolar/api/client/npolar_api_command.rb', line 27

def param
  @param
end

#uriObject

Returns the value of attribute uri.



27
28
29
# File 'lib/npolar/api/client/npolar_api_command.rb', line 27

def uri
  @uri
end

Class Method Details

.run(argv = ARGV) ⇒ Object



265
266
267
268
269
270
271
272
273
274
275
# File 'lib/npolar/api/client/npolar_api_command.rb', line 265

def self.run(argv=ARGV)
  begin
    cmd = new(argv)
    cmd.run
    exit(0)
  rescue => e
    puts e
    puts e.backtrace.join("\n")
    exit(1)
  end
end

Instance Method Details

#actionObject



261
262
263
# File 'lib/npolar/api/client/npolar_api_command.rb', line 261

def action
  param[:action]
end

#headerObject

Request header Hash Merges default client headers with command line headers (-H or –header)



135
136
137
138
139
140
141
142
# File 'lib/npolar/api/client/npolar_api_command.rb', line 135

def header
  header = client.header
  param[:header].each do |h|
    k, v = h.split(": ")
    header[k] = v
  end
  header
end

#headers?Boolean

Show response headers?

Returns:

  • (Boolean)


129
130
131
# File 'lib/npolar/api/client/npolar_api_command.rb', line 129

def headers?
  param[:headers]
end

#parametersObject

Request parameters (usually nil)



155
156
157
158
159
160
161
# File 'lib/npolar/api/client/npolar_api_command.rb', line 155

def parameters
  parameters = {}
  if param.key? :ids
    parameters = parameters.merge({"ids" => param[:ids]})
  end
  parameters
end

#pathObject

Request path (nil because base URI is already set)

Returns:

  • nil



146
147
148
# File 'lib/npolar/api/client/npolar_api_command.rb', line 146

def path
  nil
end

#runnil

Execute npolar-api command

Returns:

  • (nil)


165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
# File 'lib/npolar/api/client/npolar_api_command.rb', line 165

def run

  @client = JsonApiClient.new(uri)
  @client.log = log
  @client.header = header
  @client.param = parameters
  if param[:concurrency]
   @client.concurrency = param[:concurrency].to_i
  end

  if param[:slice]
   @client.slice = param[:slice].to_i
  end

  if uri =~ /\w+[:]\w+[@]/
    username, password = URI.parse(uri).userinfo.split(":")
    @client.username = username
    @client.password = password
  end
  
  if param[:auth]
    # Force authorization
    @client.authorization = true
  end

  method = param[:method].upcase

  response = nil

  case method
    when "DELETE"
      response = delete(path, parameters, header)
    when "GET"
      response = get(path)
    when "HEAD"
      response = head(path, parameters, header)
    when "PATCH"
      response = patch(path, parameters, header)
    when "POST"
      if data.is_a? Dir
        raise "Not implemented"
      else
        response = post(data, path, parameters, header)
      end
      
      
      
    when "PUT"
      response = put(data, path, parameters, header)
    else
      raise ArgumentError, "Unsupported HTTP method: #{param[:method]}"
  end

  #Loop dirs?
  if not response.nil? and (response.respond_to? :body or response.is_a? Array)
    if response.is_a? Array
      responses = response
    else
      responses = [response]
    end

    i = 0
    responses.each do | response |
      i += 1
      log.debug "#{method} #{response.uri.path} [#{i}] Total time: #{response.total_time}"+
        " DNS time: #{response.namelookup_time}"+
        " Connect time: #{response.connect_time}"+
        " Pre-transer time: #{response.pretransfer_time}"
        
      if "HEAD" == method or headers?
        puts response.response_headers
      end
      unless param[:join]
        puts response.body
      end
    end
    
    statuses = responses.map {|r| r.code }.uniq
    status = statuses.map {|code| { code => responses.select {|r| code == r.code }.size } }.to_json.gsub(/["{}\[\]]/, "")
    real_responses_size = responses.select {|r| r.code >= 100 }.size

    log.info "Status(es): #{status}, request(s): #{responses.size}, response(s): #{real_responses_size}"

  else
    raise "Invalid response: #{response}"
  end
  
  if param[:join]
    joined = responses.map {|r|
      JSON.parse(r.body)
    }
    puts joined.to_json
  end

end