This repository was archived by the owner on Mar 18, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathhttp.js
More file actions
173 lines (149 loc) · 5.29 KB
/
http.js
File metadata and controls
173 lines (149 loc) · 5.29 KB
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
const fetch = require('isomorphic-fetch')
const errors = require('../errors')
const utils = require('../utils')
const URL = require('url-parse')
const urlTemplate = require('url-template')
const parseResponse = (response, decoders, responseCallback) => {
return response.text().then(text => {
if (responseCallback) {
responseCallback(response, text)
}
const contentType = response.headers.get('Content-Type')
const decoder = utils.negotiateDecoder(decoders, contentType)
const options = {url: response.url}
return decoder.decode(text, options)
})
}
class HTTPTransport {
constructor (options = {}) {
this.schemes = ['http', 'https']
this.auth = options.auth || null
this.headers = options.headers || {}
this.fetch = options.fetch || fetch
this.FormData = options.FormData || window.FormData
this.requestCallback = options.requestCallback
this.responseCallback = options.responseCallback
}
buildRequest (link, decoders, params = {}) {
const fields = link.fields
const method = link.method.toUpperCase()
let queryParams = {}
let pathParams = {}
let formParams = {}
let fieldNames = []
let hasBody = false
for (let idx = 0, len = fields.length; idx < len; idx++) {
const field = fields[idx]
// Ensure any required fields are included
if (!params.hasOwnProperty(field.name)) {
if (field.required) {
throw new errors.ParameterError(`Missing required field: "${field.name}"`)
} else {
continue
}
}
fieldNames.push(field.name)
if (field.location === 'query') {
queryParams[field.name] = params[field.name]
} else if (field.location === 'path') {
pathParams[field.name] = params[field.name]
} else if (field.location === 'form') {
formParams[field.name] = params[field.name]
hasBody = true
} else if (field.location === 'body') {
formParams = params[field.name]
hasBody = true
}
}
// Check for any parameters that did not have a matching field
for (var property in params) {
if (params.hasOwnProperty(property) && !fieldNames.includes(property)) {
throw new errors.ParameterError(`Unknown parameter: "${property}"`)
}
}
let requestOptions = {method: method, headers: {}}
Object.assign(requestOptions.headers, this.headers)
if (hasBody) {
if (link.encoding === 'application/json') {
requestOptions.body = JSON.stringify(formParams)
requestOptions.headers['Content-Type'] = 'application/json'
} else if (link.encoding === 'multipart/form-data') {
let form = new this.FormData()
for (let paramKey in formParams) {
form.append(paramKey, formParams[paramKey])
}
requestOptions.body = form
} else if (link.encoding === 'application/x-www-form-urlencoded') {
let formBody = []
for (let paramKey in formParams) {
const encodedKey = encodeURIComponent(paramKey)
const encodedValue = encodeURIComponent(formParams[paramKey])
formBody.push(encodedKey + '=' + encodedValue)
}
formBody = formBody.join('&')
requestOptions.body = formBody
requestOptions.headers['Content-Type'] = 'application/x-www-form-urlencoded'
}
}
if (this.auth) {
requestOptions = this.auth.authenticate(requestOptions)
}
let parsedUrl = urlTemplate.parse(link.url)
parsedUrl = parsedUrl.expand(pathParams)
parsedUrl = new URL(parsedUrl, null, true)
parsedUrl.set('query', Object.assign(parsedUrl.query, queryParams))
// Modified querystringify to parse lists into repeated querystring keys
function querystringify (obj, prefix) {
var has = Object.prototype.hasOwnProperty
prefix = prefix || ''
var pairs = []
//
// Optionally prefix with a '?' if needed
//
if (typeof prefix !== 'string') prefix = '?'
for (var key in obj) {
if (has.call(obj, key)) {
let value = obj[key]
if (Array.isArray(value)) {
for (let item of value) {
pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(item))
}
} else {
pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(value))
}
}
}
return pairs.length ? prefix + pairs.join('&') : ''
}
return {
url: parsedUrl.toString(querystringify),
options: requestOptions
}
}
action (link, decoders, params = {}) {
const responseCallback = this.responseCallback
const request = this.buildRequest(link, decoders, params)
if (this.requestCallback) {
this.requestCallback(request)
}
return this.fetch(request.url, request.options)
.then(function (response) {
if (response.status === 204) {
return
}
return parseResponse(response, decoders, responseCallback)
.then(function (data) {
if (response.ok) {
return data
} else {
const title = response.status + ' ' + response.statusText
const error = new errors.ErrorMessage(title, data)
return Promise.reject(error)
}
})
})
}
}
module.exports = {
HTTPTransport: HTTPTransport
}