前端:基于Vue框架的调用及mock后端接口整合

      最近在搭建一个基于Vue框架的前端架构,试图探索出如何将调用后端的代码整合成一个模块,并且能方便地mock接口,返回假数据,便于与后端独立开发。现在,将实践结果进行记录,给以后及他人提供参考。

后端向前端返回的数据结构为:

{
  success: true,
  errorCode: 1000000,
  errorMsg: null,
  result: null
}

在"remote/url.js"文件中,定义调用后台的url,以及是否mock假数据

// remote/url.js
export default {
  login: '/api/login',
  logout: {url: '/api/logout', mock: true}
}

在"remote/mock.js"文件中,定义mock假数据时返回的数据

// remote/mock.js
export default {
  login: request => {
    return {
      success: true,
      errorCode: 1000000,
      errorMsg: null,
      result: {
        username: 'user',
        sessionId: '123456'
      }
    }
  },
  logout: request => {
    return {
      success: true,
      errorCode: 1000000,
      errorMsg: null,
      result: null
    }
  }
}

在"remote/index.js"主文件中,将url.js文件中定义的url映射成方法,并且提供对外调用。

toHump方法用于将返回数据的下划线表示转换成驼峰法表示

toUnderline方法用于将请求数据的驼峰法表示转换成下划线表示

// remote/index.js
import Url from './url.js'
import Mock from './mock.js'

let remote = {}
let prefix = 'http://localhost:8080'
let toHump = (obj) => {
  if (obj instanceof Object) {
    Object.keys(obj).forEach(key => {
      let newKey = key.replace(/_([a-z])/g, $1 => $1.toUpperCase()).replace(/_/g, '')
      let newValue = toHump(obj[key])
      delete obj[key]
      obj[newKey] = newValue
    })
  }
  return obj
}
let toUnderline = (obj) => {
  if (obj instanceof Object) {
    Object.keys(obj).forEach(key => {
      let newKey = key.replace(/([A-Z])/g, '_$1').toLowerCase()
      let newValue = toUnderline(obj[key])
      delete obj[key]
      obj[newKey] = newValue
    })
  }
  return obj
}
let invoke = (scope, url, request, successCallback, errorCallback) => {
  request = toUnderline(request)
  scope.$http.post(prefix + url, request).then(response => {
    console.log('call ' + url + ' success, request : ' + JSON.stringify(request) + ', response : ' + JSON.stringify(response.body))
    if (successCallback !== undefined && response.body.success) {
      successCallback(toHump(response.body))
    } else if (errorCallback !== undefined) {
      errorCallback(toHump(response.body))
    }
  }, error => {
    console.log('call ' + url + ' fail, request : ' + JSON.stringify(request) + ', error : ' + JSON.stringify(error.body))
    if (errorCallback !== undefined) {
      let res = {}
      res.success = false
      res.errorMsg = error.body.error || '系统错误'
      res.errorCode = error.body.status || 500
      errorCallback(toHump(res))
    }
  })
}
Object.keys(Url).forEach(key => {
  let value = Url[key]
  let mockVal = false
  let urlVal
  if (value instanceof Object) {
    mockVal = value.mock || false
    urlVal = value.url
  } else {
    urlVal = value
  }
  if (mockVal) {
    remote[key] = (scope, request, successCallback, errorCallback) => successCallback(Mock[key](request))
  } else {
    remote[key] = (scope, request, successCallback, errorCallback) => invoke(scope, urlVal, request, successCallback, errorCallback)
  }
})

export default remote

使用该模块的方法为,在需要的地方如下调用

import Remote from './remote/index.js'
...
Remote.login(this, {ticket: '123'}, response => {
  let user = response.result
  ...
}, error => {
  alert('登录失败' + (error.errorMsg ? ' : ' + error.errorMsg : ''))
})
...
Remote.logout(this, {}, response => {
  ...
}, error => {
  alert('退出登录失败' + (error.errorMsg ? ' : ' + error.errorMsg : ''))
})

阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭