Passed
Push — main ( 62b2dd...fb3253 )
by Pieter Epeüs
02:53 queued 44s
created

src/url-generator.js   A

Complexity

Total Complexity 15
Complexity/F 1.88

Size

Lines of Code 73
Function Count 8

Duplication

Duplicated Lines 0
Ratio 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 15
eloc 38
mnd 7
bc 7
fnc 8
dl 0
loc 73
ccs 29
cts 29
cp 1
rs 10
bpm 0.875
cpm 1.875
noi 0
c 0
b 0
f 0

7 Functions

Rating   Name   Duplication   Size   Complexity  
A URLString.setPath 0 9 3
A URLString.create 0 8 1
A URLString.constructor 0 5 1
A URLString.toString 0 10 3
A URLString.setSearchParams 0 9 3
A URLString.setUrl 0 6 2
A URLString.urlReducer 0 7 2
1
import { URL } from 'url'
2
3
export default class URLString {
4
  constructor () {
5 26
    this.url = null
6 26
    this.path = {}
7 26
    this.searchParams = {}
8
  }
9
10
  setUrl (url) {
11 26
    if (!url || url.constructor !== String) {
12 1
      throw new Error('url isnt a valid string')
13
    }
14 25
    this.url = new URL(url).href
15
  }
16
17
  setSearchParams (searchParams) {
18 23
    if (!searchParams) {
19 14
      return
20
    }
21 9
    if (searchParams.constructor !== Object) {
22 1
      throw new Error('searchParams isnt a valid object')
23
    }
24 8
    this.searchParams = searchParams
25
  }
26
27
  setPath (path) {
28 24
    if (!path) {
29 2
      return
30
    }
31 22
    if (path.constructor !== Object) {
32 1
      throw new Error('path isnt a valid object')
33
    }
34 21
    this.path = path
35
  }
36
37
  urlReducer (accumulator, [key, value]) {
38 34
    if (!value) {
39 2
      return accumulator + '/' + key
40
    }
41
42 32
    return accumulator + '/' + key + '/' + value
43
  }
44
45
  toString () {
46 22
    const completeUrl = new URL(Object.entries(this.path).reduce(this.urlReducer, this.url))
47 22
    Object.entries(this.searchParams).forEach(([searchParam, searchValue]) => {
48 9
      if (searchValue) {
49 7
        completeUrl.searchParams.append(searchParam, searchValue)
50
      }
51
    })
52
53 22
    return completeUrl.href
54
  }
55
56
  /**
57
     * Generate an url from the url, path and search params
58
     *
59
     * @param {string} url
60
     * @param {object} path
61
     * @param {object} searchParams
62
     *
63
     * @return {string}
64
     */
65
  static create ({ url, path, searchParams }) {
66 26
    const newUrl = new URLString()
67 26
    newUrl.setUrl(url)
68 24
    newUrl.setPath(path)
69 23
    newUrl.setSearchParams(searchParams)
70
71 22
    return newUrl.toString()
72
  }
73
}
74