forked from octokit/octokit.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
64 lines (50 loc) · 1.83 KB
/
index.js
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
'use strict'
module.exports = restEndpoint
const defaultsDeep = require('lodash/defaultsDeep')
const intersection = require('lodash/intersection')
const mapKeys = require('lodash/mapKeys')
const omit = require('lodash/omit')
const urlTemplate = require('url-template')
const addQueryParameters = require('./add-query-parameters')
const extractUrlVariableNames = require('./extract-url-variable-names')
const DEFAULTS = module.exports.DEFAULTS = require('./defaults')
const NON_PARAMETERS = [
'request',
'baseUrl'
]
function restEndpoint (options) {
// lowercase header names (#760)
options.headers = mapKeys(options.headers, (value, key) => key.toLowerCase())
options = defaultsDeep({}, options, DEFAULTS)
let method = options.method.toLowerCase()
let baseUrl = options.baseUrl
let url = options.url
let body = options.body
let headers = options.headers
let remainingOptions = omit(options, ['method', 'baseUrl', 'url', 'headers'])
// replace :varname with {varname} to make it RFC 6570 compatible
url = url.replace(/:([a-z]\w+)/g, '{+$1}')
// extract variable names from URL to calculate remaining variables later
const urlVariableNames = extractUrlVariableNames(url)
url = urlTemplate.parse(url).expand(remainingOptions)
if (!/^http/.test(url)) {
url = (baseUrl) + url
}
const requestOptions = remainingOptions.request
remainingOptions = omit(remainingOptions, intersection(Object.keys(options), urlVariableNames).concat(NON_PARAMETERS))
if (method === 'get' || method === 'head') {
url = addQueryParameters(url, remainingOptions)
} else {
if ('input' in remainingOptions) {
body = remainingOptions.input
} else {
body = Object.keys(remainingOptions).length ? remainingOptions : undefined
}
}
return Object.assign(requestOptions, {
method,
url,
headers,
body
})
}