liuxiaolong
2019-05-06 2ab7a76a38fbf8fa107bf6371f5410ba54e1d394
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
import qs from 'qs'
import store from '@/store'
import {
  timeout,
  request,
  httpTimeout
} from '@/server/common/request_helper'
import router from '@/router'
import toast from '@/components/common/toasted'
import {
  json2url,
  json2path,
  json2formData
} from '@/components/common/util'
require('es6-promise').polyfill()
require('isomorphic-fetch')
 
// 刷新token函数
export const refreshToken = () => {
  let refresh = JSON.parse(sessionStorage.getItem('loginedInfo')).refresh_token
  let access = JSON.parse(sessionStorage.getItem('loginedInfo')).access_token.replace('bearer ', '')
  let opts = {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    body: 'refresh_token=' + refresh + '&access_token=' + access
  }
  return fetch(request('/data/api-u/sys/refresh_token'), opts)
    .then(res => res.json())
    .then(json => {
      if (!json.code) {
        const loginedInfo = {
          'access_token': json.token_type + ' ' + json.access_token,
          'refresh_token': json.refresh_token
        }
        sessionStorage.setItem('loginedInfo', JSON.stringify(loginedInfo))
        sessionStorage.setItem('expires_in', json.expires_in)
        return {
          loginedInfo,
          expires_in: json.expires_in
        }
      } else {
        sessionStorage.removeItem('loginedInfo')
        sessionStorage.removeItem('expires_in')
        sessionStorage.removeItem('userInfo')
        router.push({
          path: '/login'
        })
        toast({
          type: 'warning',
          message: '登陆过期,请重新登陆'
        })
      }
    })
}
 
export const Frequest = ({
  method,
  url,
  type,
  body,
  header,
  isLoading = true
}) => {
  method = method.toUpperCase()
  if (body && (method === 'GET' || method === 'DELETE')) {
    if (type && type === 'path') {
      url = url + '/' + json2path(body)
    } else {
      url = url + '?' + json2url(body)
    }
    body = undefined
  } else {
    if (type && type === 'formData') {
      body = body && json2formData(body)
    } else if (header && header['Content-Type'] === 'application/x-www-form-urlencoded') {
      body = body && qs.stringify(body)
    } else {
      body = body && JSON.stringify(body)
    }
  }
  let contentType = (method === 'GET' || method === 'DELETE') ? 'application/x-www-form-urlencoded;' : (type === 'formData') ? 'multipart/form-data;' : 'application/json;'
  let token = sessionStorage.getItem('loginedInfo') && JSON.parse(sessionStorage.getItem('loginedInfo')).access_token
  let routerJson = router.history.current.query
  let opts = {
    method,
    headers: {
      'Content-Type': contentType
    },
    body
  }
  /* 获取token 两种方式 */
  if (token && token !== '') {
    opts.headers.Authorization = token
  } else if (routerJson.loginedInfo && routerJson.loginedInfo !== '') {
    opts.headers.Authorization = routerJson.loginedInfo && JSON.parse(routerJson.loginedInfo).access_token
  }
  if (header) {
    for (let name in header) {
      opts.headers[name] = header[name]
    }
  }
  /* 用于londing开启 start */
  let isResult = false
  let loadingCount = 0
  let timer = setInterval(() => {
    loadingCount++
    if (!isResult && loadingCount > 50 && isLoading) {
      store.commit('HANDLE_LOADING_OPEN')
      clearInterval(timer)
    }
  }, 10)
  /* 用于londing开启 end */
  return fetch(request(url), opts)
    .then(res => {
      if (res.ok || res.status === 400) {
        return res.json()
      } else {
        throw httpTimeout(res)
      }
    })
    .then(json => {
      isResult = true
      // 执行token 刷新方法
      if (sessionStorage.getItem('expires_in') < 100) {
        refreshToken()
      }
      clearInterval(timer)
      isLoading && store.commit('HANDLE_LOADING_CLOSE')
      return json && json
    }).catch(error => {
      error && console.warn(error, 'error')
      isResult = true
      isLoading && store.commit('HANDLE_LOADING_CLOSE')
      timeout(error)
      // clearInterval(error)
      // return error
    })
}
 
export const httpGET = (url, json) => Frequest({
  method: 'GET',
  url,
  type: json && json.type,
  body: json && json.body,
  header: json && json.header,
  isLoading: json && json.isLoading
})
export const httpPOST = (url, json) => Frequest({
  method: 'POST',
  url,
  type: json && json.type,
  body: json && json.body,
  header: json && json.header,
  isLoading: json && json.isLoading
})
export const httpPUT = (url, json) => Frequest({
  method: 'PUT',
  url,
  type: json && json.type,
  body: json && json.body,
  header: json && json.header,
  isLoading: json && json.isLoading
})
export const httpDEL = (url, json) => Frequest({
  method: 'DELETE',
  url,
  type: json && json.type,
  body: json && json.body,
  header: json && json.header,
  isLoading: json && json.isLoading
})