const app = getApp()

function unwrap(data) {
  if (data && typeof data === 'object' && 'code' in data && 'data' in data) {
    return data.data
  }
  return data
}

function request({ url, method = 'GET', data = {}, header = {} }) {
  return new Promise((resolve, reject) => {
    wx.request({
      url: `${app.globalData.baseUrl}${url.startsWith('/') ? '' : '/'}${url}`,
      method,
      data,
      header,
      success: (res) => {
        resolve(unwrap(res.data))
      },
      fail: (err) => reject(err)
    })
  })
}

module.exports = { request }
