Class: Lhj::Command::Yapi

Inherits:
Lhj::Command show all
Defined in:
lib/lhj/command/yapi.rb

Overview

generate model from yapi

Constant Summary collapse

API_INTERFACE_URL =
'api/interface/get?id='.freeze
API_PROJECT_URL =
'api/project/get?id='.freeze

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Lhj::Command

#auto_spin, #begin_title, #run, #stop

Constructor Details

#initialize(argv) ⇒ Yapi

Returns a new instance of Yapi.



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/lhj/command/yapi.rb', line 29

def initialize(argv)
  @id = argv.option('id')
  @model_pre_name = argv.option('model-pre')
  @model_result_name = argv.option('model-name')
  @webhook = argv.option('webhook')
  @language = argv.option('lan', 'oc')
  @save = argv.flag?('save', false)
  @sync = argv.flag?('sync', false)
  @notify = argv.flag?('notify', false)
  @debug = argv.flag?('debug', false)
  @sync = true if @notify
  @save = true if @sync
  @http_headers = []
  @config_id = ''
  @config_model_pre = 'ML'
  @config_model_name = 'Result'
  @config_base_url = 'http://yapi.xx.com'
  @type_trans = {}
  super
end

Class Method Details

.optionsObject



18
19
20
21
22
23
24
25
26
27
# File 'lib/lhj/command/yapi.rb', line 18

def self.options
  [
    %w[--id api的id],
    %w[--model-pre 模型的前缀],
    %w[--model-name 模型的名称],
    %w[--save 保存生成文件],
    %w[--sync 同步到github],
    %w[--notify 通知到钉钉]
  ]
end

Instance Method Details

#api_idObject



224
225
226
# File 'lib/lhj/command/yapi.rb', line 224

def api_id
  @id || @config_id.to_s
end

#api_original_url(project_id) ⇒ Object



187
188
189
# File 'lib/lhj/command/yapi.rb', line 187

def api_original_url(project_id)
  "#{@config_base_url}/project/#{project_id}/interface/api/#{api_id}"
end

#fetch_req_body(res_json) ⇒ Object



338
339
340
341
342
343
344
# File 'lib/lhj/command/yapi.rb', line 338

def fetch_req_body(res_json)
  return if !res_json || !res_json['data'] || !res_json['data']['req_body_other']

  result = JSON.parse(res_json['data']['req_body_other'])
  result['name'] = gen_model_name(nil, :req)
  result
end

#fetch_res_boy(res_json) ⇒ Object



324
325
326
327
328
329
330
331
332
333
334
335
336
# File 'lib/lhj/command/yapi.rb', line 324

def fetch_res_boy(res_json)
  return if !res_json || !res_json['data'] || !res_json['data']['res_body']

  res_body = JSON.parse(res_json['data']['res_body'])

  result = res_body
  result = res_body['properties']['detailMsg'] if res_body['properties'] && res_body['properties']['detailMsg']

  return unless result['type'] == 'object' || result['type'] == 'array'

  result['name'] = gen_model_name
  result
end

#gen_model_name(property_name = nil, type = :res) ⇒ Object



346
347
348
349
350
351
352
353
354
355
356
357
# File 'lib/lhj/command/yapi.rb', line 346

def gen_model_name(property_name = nil, type = :res)
  name = model_name
  unless property_name.nil?
    name = property_name.gsub(/vo|model|list/i, '').gsub(/(.*)s$/, '\1').gsub(/^\w/) { Regexp.last_match(0).upcase }
    name = property_name.gsub(/^\w/) { Regexp.last_match(0).upcase } if name.length <= 0
  end
  if type == :req
    "#{model_pre}#{name}#{req_model_name}"
  else
    "#{model_pre}#{name}#{model_suffix}"
  end
end

#get_interface_api_model(config) ⇒ Object



252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
# File 'lib/lhj/command/yapi.rb', line 252

def get_interface_api_model(config)
  uri = URI.parse(interface_url_str)
  req = Net::HTTP::Get.new(uri)
  header_arr = []
  config.each do |k, v|
    header_arr << "#{k}=#{v}" if k.eql?('__wpkreporterwid_') || k.eql?('_yapi_token') || k.eql?('_yapi_uid')
  end
  req['Cookie'] = header_arr.join('; ')
  res = Net::HTTP.start(uri.hostname, uri.port) do |http|
    http.request(req)
  end
  res_json = JSON.parse(res.body)
  puts res.body unless res_json['errcode'].to_i.zero?
  puts res.body if @debug
  res_json
end

#get_project_info(project_id, config) ⇒ Object



269
270
271
272
273
274
275
276
277
278
279
280
281
282
# File 'lib/lhj/command/yapi.rb', line 269

def get_project_info(project_id, config)
  url = project_url_str(project_id)
  uri = URI.parse(url)
  req = Net::HTTP::Get.new(uri)
  header_arr = []
  config.each do |k, v|
    header_arr << "#{k}=#{v}" if k.eql?('__wpkreporterwid_') || k.eql?('_yapi_token') || k.eql?('_yapi_uid')
  end
  req['Cookie'] = header_arr.join('; ')
  res = Net::HTTP.start(uri.hostname, uri.port) do |http|
    http.request(req)
  end
  JSON.parse(res.body)
end

#handleObject



50
51
52
# File 'lib/lhj/command/yapi.rb', line 50

def handle
  process(yml_file) if File.exist?(yml_file)
end

#handle_model(model, type, &block) ⇒ Object



359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
# File 'lib/lhj/command/yapi.rb', line 359

def handle_model(model, type, &block)
  p_type = model['type']
  p_name = model['name']
  p_properties = model['properties']
  p_model = { name: p_name }

  properties = []
  case p_type
  when 'object'
    p_properties.each do |k, v|
      c_type = @type_trans[v['type']] || v['type']
      c_model = { key: k, type: c_type, description: v['description'], default: '' }
      if v['type'].eql?('object') || v['type'].eql?('array')
        o = v['items'] || v
        o['name'] = gen_model_name(k, type)
        if v['type'].eql?('array') && v['items']['type'].eql?('string')
          c_model[:type_name] = 'NSString'
        else
          c_model[:type_name] = o['name']
          handle_model(o, type, &block)
        end
      end
      properties << c_model
    end
    p_model[:properties] = properties
    block[p_model] if block_given?
  when 'array'
    t = model['items']
    t['name'] = p_name
    handle_model(t, type, &block)
  end
end

#interface_url_strObject



179
180
181
# File 'lib/lhj/command/yapi.rb', line 179

def interface_url_str
  "#{@config_base_url}/#{API_INTERFACE_URL}#{api_id}"
end

#load_config(file) ⇒ Object



199
200
201
# File 'lib/lhj/command/yapi.rb', line 199

def load_config(file)
  YAML.load_file(file)
end

#model_nameObject



232
233
234
# File 'lib/lhj/command/yapi.rb', line 232

def model_name
  @model_result_name || @config_model_name
end

#model_preObject



228
229
230
# File 'lib/lhj/command/yapi.rb', line 228

def model_pre
  @model_pre_name || @config_model_pre
end

#model_suffixObject



240
241
242
# File 'lib/lhj/command/yapi.rb', line 240

def model_suffix
  @config_model_suffix || 'Model'
end

#notify_robot(upload_info, interface_info, project_info) ⇒ Object



158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
# File 'lib/lhj/command/yapi.rb', line 158

def notify_robot(upload_info, interface_info, project_info)
  i_url = "#{project_info['data']['basepath']}#{interface_info['data']['path']}"
  username = interface_info['data']['username']
  title = interface_info['data']['title']
  p_id = project_info['data']['_id']
  api_url = api_original_url(p_id)
  temp_vars = upload_info.merge({
                                  api_id: api_id,
                                  title: title,
                                  username: username,
                                  interface_url: i_url,
                                  api_url: api_url
                                })
  template = Lhj::ErbTemplateHelper.load('oc_code_notify')
  output = Lhj::ErbTemplateHelper.render(template, temp_vars, '-')
  btn_array = [
    { 'title' => '查看Yapi', 'actionURL' => api_url }
  ]
  Lhj::Dingtalk.post_card_message_robot(robot_url, 'yapi generate', output, btn_array)
end


516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
# File 'lib/lhj/command/yapi.rb', line 516

def print_http_method(data, project_info)
  return unless data

  path = data['path']
  if path
    arr = path.split('/').map do |s|
      re = s.gsub(/[^A-Za-z0-9](.)/) { Regexp.last_match(0).upcase }
      re = re.gsub(/[^A-Za-z0-9]/, '')
      re.gsub(/^\w/) { Regexp.last_match(0).upcase }
    end
    path_name = arr.join('')
  end
  path_key = "k#{path_name}URL"
  display_path = "#{project_info['data']['basepath']}#{path}"
  display_path = display_path[1..-1] if display_path.index('/') == 0
  result_model_name = gen_model_name
  param_model_name = gen_model_name(nil, :req)
  mth = data['method']
  mth = 'JSON' if data['req_body_is_json_schema']
  case @language
  when 'oc'
    puts "\n<===============方法调用=====================>\n".green
    model_temp = Lhj::ErbTemplateHelper.load('oc_code_service_inner')
    model_temp_result = Lhj::ErbTemplateHelper.render(model_temp, { result_model_name: result_model_name }, '-')

    yapi_temp = Lhj::ErbTemplateHelper.load('oc_code_service')
    yapi_vars = { title: data['title'],
                  desc: data['desc'],
                  username: data['username'],
                  path: display_path,
                  path_key: path_key,
                  path_name: path_name,
                  result_model_name: result_model_name,
                  param_model_name: param_model_name,
                  mth: mth,
                  model_template: model_temp_result }
    yapi_temp_result = Lhj::ErbTemplateHelper.render(yapi_temp, yapi_vars, '-')
    puts yapi_temp_result.green
    return yapi_temp_result
  when 'java'
  end

end


560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
# File 'lib/lhj/command/yapi.rb', line 560

def print_mock_request_data(req_models)
  puts "\n<===============打印Mock Data-Begin=====================>\n".green
  req_models.each do |model|
    model_name = model[:name] || ''
    model_properties = model[:properties]
    puts_mock "#{model_name} *mock = [[#{model_name} alloc] init];"
    model_properties.each do |m|
      puts_mock "/// #{m[:description]}"
      type = m[:type]
      case type
      when 'integer'
        puts_mock "mock.#{m[:key]} = 0;"
      when 'number'
        puts_mock "mock.#{m[:key]} = 0;"
      when 'float'
        puts_mock "mock.#{m[:key]} = 0;"
      when 'double'
        puts_mock "mock.#{m[:key]} = 0;"
      when 'object'
        puts_mock "mock.#{m[:key]} = @{};"
      when 'array'
        puts_mock "mock.#{m[:key]} = @[];"
      else
        puts_mock "mock.#{m[:key]} = @\"\";"
      end
    end
    puts_mock "\n\n"
  end
  puts "\n<===============打印Mock Data-End=====================>\n".green
end


439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
# File 'lib/lhj/command/yapi.rb', line 439

def print_model(m)
  key = m[:key]
  key = property_mapper[key] if property_mapper.keys.include?(key)
  type_name = m[:type_name]
  type = m[:type]
  des = m[:description] || ''
  des.gsub!(/\n/, '  ')
  default = m[:default]
  puts_h "///#{des} #{default}"
  case type
  when 'integer'
    puts_h "@property (nonatomic, assign) NSInteger #{key};"
  when 'string'
    puts_h "@property (nonatomic, copy) NSString *#{key};"
  when 'number'
    puts_h "@property (nonatomic, strong) NSNumber *#{key};"
  when 'float'
    puts_h "@property (nonatomic, assign) CGFloat #{key};"
  when 'double'
    puts_h "@property (nonatomic, assign) double #{key};"
  when 'boolean'
    puts_h "@property (nonatomic, assign) BOOL #{key};"
  when 'object'
    puts_h "@property (nonatomic, strong) #{type_name} *#{key};"
  when 'array'
    puts_h "@property (nonatomic, strong) NSArray<#{type_name} *> *#{key};"
  else
    puts_h "@property (nonatomic, copy) NSString *#{key};"
  end
end


470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
# File 'lib/lhj/command/yapi.rb', line 470

def print_model_for_java(m)
  key = m[:key]
  type_name = m[:type_name]
  type = m[:type]
  des = m[:description] || ''
  des.gsub!(/\n/, '  ')
  default = m[:default]
  case type
  when 'integer'
    puts_h "int #{key};//#{des} #{default}"
  when 'string'
    puts_h "String #{key};//#{des} #{default}"
  when 'number'
    puts_h "double #{key};//#{des} #{default}"
  when 'float'
    puts_h "double #{key};//#{des} #{default}"
  when 'double'
    puts_h "double #{key};//#{des} #{default}"
  when 'boolean'
    puts_h "boolean #{key};//#{des} #{default}"
  when 'object'
    puts_h "#{type_name} #{key};//#{des} #{default}"
  when 'array'
    puts_h "#{type_name}[] #{key};//#{des} #{default}"
  else
    puts_h "String #{key};//#{des} #{default}"
  end
end


392
393
394
395
396
397
398
399
400
401
402
# File 'lib/lhj/command/yapi.rb', line 392

def print_models(models)
  models.each do |model|
    model_name = model[:name] || ''
    model_properties = model[:properties]
    puts_h "@interface #{model_name} : NSObject"
    model_properties.each do |m|
      print_model(m)
    end
    puts_h "@end\n\n\n"
  end
end


404
405
406
407
408
409
410
411
412
413
414
# File 'lib/lhj/command/yapi.rb', line 404

def print_models_for_java(models)
  models.each do |model|
    model_name = model[:name] || ''
    model_properties = model[:properties]
    puts_h "public class #{model_name} extends BaseModel implements BusinessEvent.ProductDataCollect {"
    model_properties.each do |m|
      print_model_for_java(m)
    end
    puts_h "}\n\n\n"
  end
end


416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
# File 'lib/lhj/command/yapi.rb', line 416

def print_models_impl(models)
  models.each do |model|
    puts_m "@implementation #{model[:name]}"
    str = model[:properties].filter { |p| p[:type].eql?('array') && !p[:type_name].eql?('NSString') }.map { |p| "@\"#{p[:key]}\": #{p[:type_name]}.class" }.join(', ')
    if str&.length&.positive?
      puts_m '+(NSDictionary *)modelContainerPropertyGenericClass {'
      puts_m "  return @{#{str}};"
      puts_m '}'
    end
    properties = model[:properties].filter { |p| property_mapper.keys.include?(p[:key]) }.map do |p|
      "@\"#{property_mapper[p[:key]]}\": @\"#{p[:key]}\""
    end
    property_mapper_str = properties.join(', ') if properties.count.positive?
    if property_mapper_str&.length&.positive?
      puts_m '+ (NSDictionary<NSString *, id> *)modelCustomPropertyMapper {'
      puts_m "  return @{#{property_mapper_str}};"
      puts_m '}'
    end
    puts_m "@end\n"
    puts "\n\n"
  end
end


304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
# File 'lib/lhj/command/yapi.rb', line 304

def print_req_body_model(res_json)
  req_body = fetch_req_body(res_json)
  return unless req_body

  puts "\n<===============打印请求模型-Begin=====================>\n".green
  models = []
  handle_model(req_body, :req) do |model|
    models << model
  end
  case @language
  when 'oc'
    print_models(models)
    print_models_impl(models)
  when 'java'
    print_models_for_java(models)
  end
  puts "\n<===============打印请求模型-End=====================>\n".green
  models
end

Parameters:

  • data (Object)


500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
# File 'lib/lhj/command/yapi.rb', line 500

def print_req_query(data)
  return unless data && data['req_query']

  properties = []
  data['req_query'].each do |h|
    properties << { key: h['name'], type: 'string', description: h['desc'], default: '' }
  end
  param_model_name = gen_model_name(nil, :req)
  req_model = { name: param_model_name, properties: properties }

  models = [req_model]
  print_models(models)
  print_models_impl(models)
  models
end


284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
# File 'lib/lhj/command/yapi.rb', line 284

def print_res_body_model(res_json)
  res_body = fetch_res_boy(res_json)
  return unless res_body

  puts "\n<===============打印返回数据模型-Begin=====================>\n".green
  models = []
  handle_model(res_body, :res) do |model|
    models << model
  end
  case @language
  when 'oc'
    print_models(models)
    print_models_impl(models)
  when 'java'
    print_models_for_java(models)
  end
  puts "\n<===============打印返回数据模型-End=====================>\n".green
  models
end

#process(config_file) ⇒ Object



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
# File 'lib/lhj/command/yapi.rb', line 54

def process(config_file)
  config = load_config(config_file)
  process_config(config)
  res_body = get_interface_api_model(config)
  unless res_body['errcode'].to_i.zero?
    if File.exist?(user_yml_file)
      user_infos = load_config(user_yml_file)
      user_infos.each do |c|
        res_body = get_interface_api_model(c)
        config = c
        break if res_body['errcode'].to_i.zero?
      end
      save_config(config) if res_body['errcode'].to_i.zero?
    end
  end
  unless res_body['errcode'].to_i.zero?
    Actions.sh('lhj yapi-init', log: false)
    return
  end
  return unless res_body && !res_body.empty?

  # get project info
  project_id = res_body['data']['project_id']
  project_info = get_project_info(project_id, config)
  # 1.print request result
  res_models = print_res_body_model(res_body)
  # 2.print request json body
  req_models = print_req_body_model(res_body) if res_body['data']['req_body_is_json_schema']
  # 3.print request param
  req_models ||= print_req_query(res_body['data']) unless res_body['data']['req_body_is_json_schema']
  # 4.print request method
  service_code = print_http_method(res_body['data'], project_info)
  # print request mock data
  print_mock_request_data(req_models) if !req_models.nil? && !req_models.empty?
  # 5.save to file
  file_map = save_to_file(service_code) if @save
  # 6.push to git
  push_to_git if @sync
  # 7.notify robot
  notify_robot(file_map, res_body, project_info) if @notify
end

#process_config(config) ⇒ Object



203
204
205
206
207
208
209
210
211
212
# File 'lib/lhj/command/yapi.rb', line 203

def process_config(config)
  @config_base_url = config['base_url']
  @config_id = config['id']
  @config_model_pre = config['model_pre']
  @config_model_suffix = config['model_suffix']
  @config_model_name = config['model_name']
  @config_robot_url = config['dingtalk']
  @type_trans = config['type_trans']
  @config_property_mapper = config['property_mapper']
end

#project_url_str(project_id) ⇒ Object



183
184
185
# File 'lib/lhj/command/yapi.rb', line 183

def project_url_str(project_id)
  "#{@config_base_url}/#{API_PROJECT_URL}#{project_id}"
end

#property_mapperObject



248
249
250
# File 'lib/lhj/command/yapi.rb', line 248

def property_mapper
  @config_property_mapper || { 'id' => 'gid' }
end

#push_to_gitObject



151
152
153
154
155
156
# File 'lib/lhj/command/yapi.rb', line 151

def push_to_git
  Actions.sh('git checkout master', log: false)
  Actions.sh('git add .', log: false)
  Actions.sh("git commit -m 'generate yapi code'", log: false)
  Actions.sh('git push', log: false)
end

#puts_h(str) ⇒ Object



96
97
98
99
100
# File 'lib/lhj/command/yapi.rb', line 96

def puts_h(str)
  puts str.magenta
  @h_file_array ||= []
  @h_file_array << str
end

#puts_h_red(str) ⇒ Object



102
103
104
105
106
# File 'lib/lhj/command/yapi.rb', line 102

def puts_h_red(str)
  puts str.red
  @h_file_array ||= []
  @h_file_array << str
end

#puts_m(str) ⇒ Object



108
109
110
111
112
# File 'lib/lhj/command/yapi.rb', line 108

def puts_m(str)
  puts str.blue
  @m_file_array ||= []
  @m_file_array << str
end

#puts_mock(str) ⇒ Object



114
115
116
117
118
# File 'lib/lhj/command/yapi.rb', line 114

def puts_mock(str)
  puts str.green
  @req_mock_array ||= []
  @req_mock_array << str
end

#req_model_nameObject



236
237
238
# File 'lib/lhj/command/yapi.rb', line 236

def req_model_name
  'RequestParam'
end

#robot_urlObject



244
245
246
# File 'lib/lhj/command/yapi.rb', line 244

def robot_url
  @webhook || @config_robot_url || 'https://oapi.dingtalk.com/robot/send?access_token=fe879fd3e7a3b5e59d5719b2384845b7884901919be5a78fe443cbf777869807'
end

#save_config(config) ⇒ Object



214
215
216
217
218
219
220
221
222
# File 'lib/lhj/command/yapi.rb', line 214

def save_config(config)
  yml = load_config(yml_file)
  yml['__wpkreporterwid_'] = config['__wpkreporterwid_']
  yml['_yapi_uid'] = config['_yapi_uid']
  yml['_yapi_token'] = config['_yapi_token']
  file_to_save = File.open(yml_file, 'w+')
  YAML.dump(yml, file_to_save)
  file_to_save.close
end

#save_to_file(service_code) ⇒ Object



128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
# File 'lib/lhj/command/yapi.rb', line 128

def save_to_file(service_code)
  name = model_name
  file_name = gen_model_name
  FileUtils.mkdir_p(File.expand_path(sub_folder_name, '.')) unless File.exist?(File.expand_path(sub_folder_name, '.'))
  h_file = File.join('.', sub_folder_name, "#{file_name}.h")
  m_file = File.join('.', sub_folder_name, "#{file_name}.m")
  service_file = File.join('.', sub_folder_name, "#{model_pre}#{name}Service.m")
  req_mock_file = File.join('.', sub_folder_name, "#{model_pre}#{name}Mock.m")

  File.write(h_file, @h_file_array.join("\n")) if @h_file_array.count.positive?
  File.write(m_file, @m_file_array.join("\n")) if @m_file_array.count.positive?
  File.write(service_file, service_code) if service_code
  File.write(req_mock_file, @req_mock_array.join("\n")) if @req_mock_array&.count&.positive?

  puts "\n\n生成文件成功!所在路径:\n#{File.expand_path(h_file)} \n#{File.expand_path(m_file)}".green if @save && !@notify
  {
    h_file: "#{sub_folder_name}/#{file_name}.h",
    m_file: "#{sub_folder_name}/#{file_name}.m",
    s_file: "#{sub_folder_name}/#{model_pre}#{name}Service.m",
    req_mock_file: "#{sub_folder_name}/#{model_pre}#{name}Mock.m"
  }
end

#sub_folder_nameObject



120
121
122
123
124
125
126
# File 'lib/lhj/command/yapi.rb', line 120

def sub_folder_name
  return @sub_folder_name if @sub_folder_name

  time = Time.now
  @sub_folder_name ||= time.strftime('%Y%m%d%H%M%S')
  @sub_folder_name
end

#user_yml_fileObject



195
196
197
# File 'lib/lhj/command/yapi.rb', line 195

def user_yml_file
  File.join(Lhj::Config.instance.home_dir, 'yapi_user.yml')
end

#yml_fileObject



191
192
193
# File 'lib/lhj/command/yapi.rb', line 191

def yml_file
  File.join(Lhj::Config.instance.home_dir, 'yapi.yml')
end