Created
September 29, 2016 23:37
-
-
Save erichulburd/dd136d5ea7ea5cfe4c6dd7faa08ef3d8 to your computer and use it in GitHub Desktop.
Spike Route class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as S from 'underscore.string'; | |
import queryString from 'query-string'; | |
export default class Route { | |
constructor(route_definition){ | |
let route = this; | |
route.params = {}; | |
route.data = route_definition; | |
} | |
get key(){ | |
return S.underscored(this.name); | |
} | |
get name(){ | |
return this.data.name; | |
} | |
get parameters(){ | |
return this.data.parameters; | |
} | |
get path(){ | |
return this.data.path; | |
} | |
get component(){ | |
return require(`shared/components/layouts/${this.key}/${this.key}.component`)[this.name]; | |
} | |
matchesLocation(pathname){ | |
let route = this; | |
return route.path.test(pathname); | |
} | |
// location is a React History location object. | |
parseParams(location){ | |
let route = this, | |
match = location.pathname.match(route.path), | |
params = {}; | |
if (match){ | |
for (let i in route.parameters){ | |
let param = route.parameters[i], | |
value = match[parseInt(i)]; | |
params[param] = value; | |
} | |
if (location.query){ | |
let query = location.query; | |
if (typeof query === 'string'){ | |
query = queryString.parse(query); | |
} | |
Object.assign(params, query); | |
} | |
} | |
this.params = params; | |
return params; | |
} | |
// route should override if it must use state to generate url | |
url(payload, i18n){ | |
if (this.data.url){ | |
return this.data.url.call(this, payload, i18n); | |
} else { | |
let route_path = i18n.t(this.key); | |
return `/${i18n.language}/${route_path}`; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment