Skip to content

request util 层的实现基于 axios 重新整理 #73

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Mar 22, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions app/backendAPI/fileAPI.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/* @flow weak */
import { request, querystring as qs } from '../utils'
import { request, qs } from '../utils'
import config from '../config'
import axios from 'axios'

Expand Down Expand Up @@ -37,7 +37,7 @@ export function writeFile (path, content, base64) {
return request({
method: 'PUT',
url: `/workspaces/${config.spaceKey}/files`,
form: {
data: {
path: path,
content: content,
base64: base64 || false,
Expand All @@ -62,7 +62,7 @@ export function createFile (path) {
return request({
method: 'POST',
url: `/workspaces/${config.spaceKey}/files`,
form: {
data: {
path: path
}
})
Expand All @@ -72,7 +72,7 @@ export function moveFile (from, to, force = false) {
return request({
method: 'POST',
url: `/workspaces/${config.spaceKey}/move`,
form: {
data: {
from: from,
to: to,
force: force
Expand All @@ -84,7 +84,7 @@ export function deleteFile (path) {
return request({
method: 'DELETE',
url: `/workspaces/${config.spaceKey}/files`,
qs: {
params: {
path: path,
recursive: true
}
Expand All @@ -95,7 +95,7 @@ export function searchFile (value, includeNonProjectItems = false) {
return request({
method: 'POST',
url: `/workspaces/${config.spaceKey}/search`,
form: {
data: {
keyword: value,
includeNonProjectItems: includeNonProjectItems
}
Expand Down
4 changes: 3 additions & 1 deletion app/backendAPI/gitAPI.js
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,9 @@ export function gitRebaseOperate ({operation, message}) {
}

export function gitRebaseUpdate (lines) {
return request.postJSON(`/git/${config.spaceKey}/rebase/update`, lines)
return request.post(`/git/${config.spaceKey}/rebase/update`, lines,
{ headers: { 'Content-Type': 'application/json' } }
)
}

export function gitCommitDiff ({ref}) {
Expand Down
11 changes: 3 additions & 8 deletions app/backendAPI/workspaceAPI.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,12 +46,7 @@ export function switchVersion () {
export function getUserProfile () {
// @fixme: platform v1 api
// return request.get('/user/current').then(res => res.data)
return request({
method: 'GET',
baseURL: config.baseURL,
url: '/user/current',
headers: {
'X-Requested-With': 'XMLHttpRequest',
},
}).then(res => res.data)
return request.get('/user/current', null,
{ headers: { 'Accept': '*/*' } }
).then(res => res.data)
}
2 changes: 1 addition & 1 deletion app/containers/Root/actions.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// import { createAction } from 'redux-actions'
import config from '../../config'
import ide from '../../IDE'
import qs from 'query-string'
import qs from 'qs'

// initAppState
export const INIT_STATE = 'INIT_STATE'
Expand Down
2 changes: 1 addition & 1 deletion app/containers/Root/reducer.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/* @flow weak */
import { handleActions } from 'redux-actions'
import qs from 'query-string'
import qs from 'qs'
import config from '../../config'

import {
Expand Down
5 changes: 2 additions & 3 deletions app/initialize.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React from 'react'
import qs from 'query-string'
import qs from 'qs'
import { bindActionCreators } from 'redux'
import config from './config'
import api from './backendAPI'
Expand All @@ -21,9 +21,8 @@ async function initialize () {
const wsPathPattern = /^\/ws\/([^\/]+)$/
const match = wsPathPattern.exec(urlPath)
if (match) spaceKey = match[1]
} else {
spaceKey = qs.parse(window.location.hash.slice(1)).spaceKey
}
if (!spaceKey) spaceKey = qs.parse(window.location.hash.slice(1)).spaceKey
if (spaceKey) config.spaceKey = spaceKey
return true
})
Expand Down
2 changes: 1 addition & 1 deletion app/utils/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export createI18n from './createI18n'
export update from './immutableUpdate'
export Model from './model'
export { getExtensions } from './extensions.js'
export { querystring } from './url-helpers'
export { default as qs } from 'qs'
export stepFactory from './stepFactory'
export loadStyle from './loadStyle'
export codingPackageJsonp from './codingPackageJsonp'
183 changes: 62 additions & 121 deletions app/utils/request.js
Original file line number Diff line number Diff line change
@@ -1,152 +1,93 @@
/* @flow weak */
import { urlJoin, querystring as qs } from './url-helpers'
import config from '../config'
import axios from 'axios'
window.axios = axios
import qs from 'qs'
import config from '../config'

const defaultRequestOptions = {
method: 'GET',
const request = axios.create({
baseURL: config.baseURL,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
...(config.isPlatform && {
'X-Requested-With': 'XMLHttpRequest',
'Accept': 'application/vnd.coding.v2+json'
})
}
}

const defaultFetchOptions = {
method: 'GET',
},
mode: 'cors',
withCredentials: true,
redirect: 'manual'
}

function interceptResponse (response) {
if (config.isPlatform && response.headers['requests-auth'] === '1') {
const authUrl = response.headers['requests-auth-url']
return location.href = authUrl
}
return response.data
}


function handleErrorResponse (response) {
return response
}

function request (_options) {
var options = Object.assign({}, defaultRequestOptions, _options)
var queryString, fetchOptions
if (options.json) {
options.headers['Content-Type'] = 'application/json'
options.body = options.json
}

if (options.form) {
options.headers['Content-Type'] = 'application/x-www-form-urlencoded'
options.body = options.form
}

if (options.body) {
options.body = (function () {
switch (options.headers['Content-Type']) {
case 'application/json':
return JSON.stringify(options.body)
case 'application/x-www-form-urlencoded':
return qs.stringify(options.body)
default:
return options.body
}
})()
}
// only applicable for request methods 'PUT', 'POST', and 'PATCH'
transformRequest: [function (data, headers) {
switch (headers['Content-Type']) {
case 'application/json':
return JSON.stringify(data)
case 'application/x-www-form-urlencoded':
return qs.stringify(data)
default:
return data
}
}]
})

const requestInterceptor = request.interceptors.request.use(function (options) {
if (config.isPlatform && config.spaceKey) {
options.headers['X-Space-Key'] = config.spaceKey
}

fetchOptions = Object.assign({}, defaultFetchOptions, {
method: options.method,
headers: options.headers || {},
data: options.body
})


var url = options.absURL ? options.absURL : urlJoin(options.baseURL, options.url)
url += (options.qs ? '?' : '') + qs.stringify(options.qs)
return axios(url, fetchOptions).then(interceptResponse).catch(handleErrorResponse)
}

function parseMethodArgs (url, data, METHOD) {
var options = {}
options.method = METHOD
if (typeof url === 'object') {
options = url
} else if (typeof url === 'string') {
if (/^https?:\/\//.test(url)) options.absURL = url
options.url = url
switch (METHOD) {
case 'GET':
case 'DELETE':
options.qs = data
break
case 'POST':
case 'PUT':
case 'PATCH':
options.form = data
break
case 'POST_JSON':
options.json = data
options.method = 'POST'
break
default:
options.data = data
}
}
return options
}

request.get = function (url, data) {
return request(parseMethodArgs(url, data, 'GET'))
}
})

request.diff = function (url, data) {
let options = parseMethodArgs(url, data, 'GET')
options.headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/vnd.coding.v2.diff+json'
}
return request(options)
}

request.diffFilesList = function (url, data) {
let options = parseMethodArgs(url, data, 'GET')
options.headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/vnd.coding.v2.diff-files-list+json'
const responseInterceptor = request.interceptors.response.use(function (response) {
if (config.isPlatform && response.headers['requests-auth'] === '1') {
const authUrl = response.headers['requests-auth-url']
return location.href = authUrl
}
return request(options)
return response.data
})

request.get = function (url, params, options={}) {
return request({
method: 'get',
url,
params,
...options,
})
}

request.post = function (url, data) {
return request(parseMethodArgs(url, data, 'POST'))
request.delete = function (url, params, options={}) {
return request({
method: 'delete',
url,
params,
...options,
})
}

request.postJSON = function (url, data) {
return request(parseMethodArgs(url, data, 'POST_JSON'))
request.diff = function (url, params, options={}) {
return request({
url,
params,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/vnd.coding.v2.diff+json',
},
...options,
})
}

request.put = function (url, data) {
return request(parseMethodArgs(url, data, 'PUT'))
request.diffFilesList = function (url, params, options={}) {
return request({
url,
params,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/vnd.coding.v2.diff-files-list+json',
},
...options,
})
}

request.patch = function (url, data) {
return request(parseMethodArgs(url, data, 'PATCH'))
request.raw = function (options) {
return axios(options)
}

request.delete = function (url, data) {
return request(parseMethodArgs(url, data, 'DELETE'))
}
request.axios = axios

export default request
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@
"lodash": "^4.14.2",
"markdown": "^0.5.0",
"octicons": "^4.3.0",
"querystring": "^0.2.0",
"qs": "^6.4.0",
"react": "^15.3.0",
"react-dom": "^15.3.1",
"react-notification": "^6.1.1",
Expand Down
4 changes: 2 additions & 2 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -4090,7 +4090,7 @@ q@^1.1.2:
version "1.4.1"
resolved "http://registry.npm.taobao.org/q/download/q-1.4.1.tgz#55705bcd93c5f3673530c2c2cbc0c2b3addc286e"

qs@~6.4.0, qs@6.4.0:
qs, qs@~6.4.0, qs@6.4.0:
version "6.4.0"
resolved "http://registry.npm.taobao.org/qs/download/qs-6.4.0.tgz#13e26d28ad6b0ffaa91312cd3bf708ed351e7233"

Expand All @@ -4105,7 +4105,7 @@ querystring-es3@^0.2.0:
version "0.2.1"
resolved "http://registry.npm.taobao.org/querystring-es3/download/querystring-es3-0.2.1.tgz#9ec61f79049875707d69414596fd907a4d711e73"

querystring@^0.2.0, querystring@0.2.0:
querystring@0.2.0:
version "0.2.0"
resolved "http://registry.npm.taobao.org/querystring/download/querystring-0.2.0.tgz#b209849203bb25df820da756e747005878521620"

Expand Down