Total Complexity | 10 |
Complexity/F | 1.67 |
Lines of Code | 51 |
Function Count | 6 |
Duplicated Lines | 0 |
Ratio | 0 % |
Changes | 2 | ||
Bugs | 1 | Features | 0 |
1 | import pathToRegexp from 'path-to-regexp'; |
||
2 | import { stringify as qsStringify } from 'query-string'; |
||
3 | import { createPath } from 'history'; |
||
4 | import { flattenRoutes } from './util'; |
||
5 | import RouterError from '../error'; |
||
6 | |||
7 | const ERRORS = { |
||
8 | noId: _ => 'Can\'t match route with no id', |
||
|
|||
9 | notFound: id => `Route with id ${id} not found` |
||
10 | }; |
||
11 | |||
12 | const createMatchRouteToPath = registry => ({ id, params = {}, query = {}, hash = ''}) => { |
||
13 | if (id === undefined) throw new RouterError(ERRORS.noId()); |
||
14 | |||
15 | const matcher = registry[id]; |
||
16 | |||
17 | if (matcher === undefined) throw new RouterError(ERRORS.notFound(id)); |
||
18 | |||
19 | let pathname; |
||
20 | |||
21 | try { |
||
22 | // path-to-regexp (1.6.0): encodeURI by default, disable it with decodeURI |
||
23 | // 'pretty' flag disable all encoding, besides '/', '?', '#' |
||
24 | pathname = decodeURIComponent(matcher(params)); |
||
25 | } catch (e) { |
||
26 | throw new RouterError(e.toString()); |
||
27 | } |
||
28 | |||
29 | const location = { |
||
30 | search: qsStringify(query), |
||
31 | pathname, |
||
32 | hash |
||
33 | }; |
||
34 | |||
35 | return createPath(location); |
||
36 | }; |
||
37 | |||
38 | const createRouteToLocationParser = routes => { |
||
39 | |||
40 | const registry = flattenRoutes(routes).reduce((result, item) => { |
||
41 | if (result[item.id]) { |
||
42 | return result; |
||
43 | } |
||
44 | result[item.id] = pathToRegexp.compile(item.pattern.path); |
||
45 | return result; |
||
46 | }, {}); |
||
47 | |||
48 | return createMatchRouteToPath(registry); |
||
49 | }; |
||
50 | |||
51 | export default createRouteToLocationParser; |
This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.