Passed
Branch feature/first-draft (480f87)
by Pieter Epeüs
03:34
created

URLString.create   A

Complexity

Conditions 1

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 6
dl 0
loc 8
c 0
b 0
f 0
ccs 5
cts 5
cp 1
rs 10
cc 1
crap 1
1
export default class URLString {
2
  constructor () {
3 24
    this.url = null
4 24
    this.path = {}
5 24
    this.searchParams = {}
6
  }
7
8
  setUrl (url) {
9 24
    if (!url || url.constructor !== String) {
10 1
      throw new Error('url isnt a valid string')
11
    }
12 23
    this.url = new URL(url).href
0 ignored issues
show
Bug introduced by
The variable URL seems to be never declared. If this is a global, consider adding a /** global: URL */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
13
  }
14
15
  setSearchParams (searchParams) {
16 21
    if (!searchParams) {
17 12
      return
18
    }
19 9
    if (searchParams.constructor !== Object) {
20 1
      throw new Error('searchParams isnt a valid object')
21
    }
22 8
    this.searchParams = searchParams
23
  }
24
25
  setPath (path) {
26 22
    if (!path) {
27 1
      return
28
    }
29 21
    if (path.constructor !== Object) {
30 1
      throw new Error('path isnt a valid object')
31
    }
32 20
    this.path = path
33
  }
34
35
  urlReducer (accumulator, [key, value]) {
36 32
    if (!value) {
37 2
      return accumulator + '/' + key
38
    }
39
40 30
    return accumulator + '/' + key + '/' + value
41
  }
42
43
  toString () {
44 20
    const completeUrl = new URL(Object.entries(this.path).reduce(this.urlReducer, this.url))
0 ignored issues
show
Bug introduced by
The variable URL seems to be never declared. If this is a global, consider adding a /** global: URL */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
45 20
    Object.entries(this.searchParams).forEach(([searchParam, searchValue]) => {
46 9
      if (searchValue) {
47 7
        completeUrl.searchParams.append(searchParam, searchValue)
48
      }
49
    })
50
51 20
    return completeUrl.href
52
  }
53
54
  /**
55
     * Generate an url from the url, path and search params
56
     *
57
     * @param {string} url
58
     * @param {object} path
59
     * @param {object} searchParams
60
     *
61
     * @return {string}
62
     */
63
  static create ({ url, path, searchParams }) {
64 24
    const newUrl = new URLString()
65 24
    newUrl.setUrl(url)
66 22
    newUrl.setPath(path)
67 21
    newUrl.setSearchParams(searchParams)
68
69 20
    return newUrl.toString()
70
  }
71
}
72