-
Notifications
You must be signed in to change notification settings - Fork 8
/
buildFullUrl.ts
73 lines (71 loc) · 1.91 KB
/
buildFullUrl.ts
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
import kebabCase from 'lodash/kebabCase'
import type { Options } from '../types'
export default function buildFullUrl(opts: Options) {
let url: string = opts.baseUrl || ''
let endpoint = kebabCase(opts.name)
let qs = null
if (opts.urlParser) {
endpoint = opts.urlParser(opts.name || '')
}
if (opts.path) {
endpoint = opts.path
}
if (opts.id && !opts.customPath) {
endpoint += '/'
endpoint += opts.id
}
if (opts.customPath) {
endpoint = opts.customPath
}
endpoint = endpoint.split('//').join('/')
if (endpoint.indexOf('/') == 0) {
let arrayEndpoint = endpoint.split('')
arrayEndpoint.shift()
endpoint = arrayEndpoint.join('')
}
if (endpoint && url.lastIndexOf('/') != url.length - 1) {
url += '/'
}
url += endpoint
if (opts.query) {
qs = ''
let options = Object.keys(opts.query)
for (let i = 0; i < options.length; i++) {
let value = opts.query[options[i]]
if (value == null || Number.isNaN(value) || typeof value == undefined) {
delete opts.query[options[i]]
}
}
options = Object.keys(opts.query)
for (let i = 0; i < options.length; i++) {
let value = opts.query[options[i]]
let name = opts.queryStringParser
? opts.queryStringParser(options[i])
: options[i]
if (
(typeof value == 'string' ||
typeof value == 'number' ||
typeof value == 'boolean') &&
!Number.isNaN(value)
) {
qs += name + '=' + value
} else {
value = value as Array<any>
for (let u = 0; u < value.length; u++) {
qs += name + '[]=' + value[u]
if (u < value.length - 1) qs += '&'
}
}
if (i < options.length - 1) qs += '&'
}
}
if (url.lastIndexOf('/') == url.length - 1) {
let arrayUrl = url.split('')
arrayUrl.pop()
url = arrayUrl.join('')
}
if (qs != null) {
url += '?' + qs
}
return url
}