Class: JPSClient::Response

Inherits:
Object
  • Object
show all
Defined in:
lib/jpsclient/http/http_client.rb

Overview

JPS API 响应封装类 - 简化版

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(http_response) ⇒ Response

Returns a new instance of Response.



243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
# File 'lib/jpsclient/http/http_client.rb', line 243

def initialize(http_response)
  @success = http_response[:success]
  @need_login = http_response[:need_login]

  if http_response[:body].is_a?(Hash)
    # 处理 Meta 格式响应: {meta: {code: 0, message: "..."}, data: {...}}
    if http_response[:body]['meta']
      @code = http_response[:body]['meta']['code']
      @msg = http_response[:body]['meta']['message']
      @data = http_response[:body]['data']
    # 处理直接格式响应: {code: 0, data: {...}, msg: "..."}
    else
      @code = http_response[:body]['code'] || http_response[:code]
      @data = http_response[:body]['data']
      @msg = http_response[:body]['msg'] || http_response[:body]['message']
    end
  else
    @code = http_response[:code]
    @data = http_response[:body]
  end
end

Instance Attribute Details

#codeObject (readonly)

Returns the value of attribute code.



239
240
241
# File 'lib/jpsclient/http/http_client.rb', line 239

def code
  @code
end

#dataObject (readonly)

Returns the value of attribute data.



240
241
242
# File 'lib/jpsclient/http/http_client.rb', line 240

def data
  @data
end

#msgObject (readonly)

Returns the value of attribute msg.



241
242
243
# File 'lib/jpsclient/http/http_client.rb', line 241

def msg
  @msg
end

Instance Method Details

#need_login?Boolean

20001: 登录token失效

Returns:

  • (Boolean)


271
272
273
# File 'lib/jpsclient/http/http_client.rb', line 271

def need_login?
  @need_login || @code.to_s == '20001'
end

#no_permission?Boolean

20011: 没有权限访问项目

Returns:

  • (Boolean)


276
277
278
# File 'lib/jpsclient/http/http_client.rb', line 276

def no_permission?
  @code.to_s == '20011'
end

#success?Boolean

Returns:

  • (Boolean)


265
266
267
268
# File 'lib/jpsclient/http/http_client.rb', line 265

def success?
  # 成功码从 200 改为 0,同时向后兼容 200
  @success && (@code.to_s == '0' || @code.to_s == '200')
end

#to_hObject



280
281
282
283
284
285
286
# File 'lib/jpsclient/http/http_client.rb', line 280

def to_h
  {
    'code' => @code,
    'data' => @data,
    'msg' => @msg
  }
end

#to_h_with_metaObject

添加新方法返回 meta 格式响应



289
290
291
292
293
294
295
296
297
# File 'lib/jpsclient/http/http_client.rb', line 289

def to_h_with_meta
  {
    'meta' => {
      'code' => @code,
      'message' => @msg
    },
    'data' => @data
  }
end