Skip to content

Instantly share code, notes, and snippets.

@KidkArolis KidkArolis/next-2.js Secret
Created Dec 5, 2018

Embed
What would you like to do?
5 Tips for Building a Next.js App (2)
import qs from 'querystring'
// a dsl for defining reverse routes
const patterns = {
'/': ['page', query => (query.page > 1 ? '/page/:page' : '/')]
}
// for clearing falsy query params out
function clean (obj) {
obj = Object.assign({}, obj)
Object.keys(obj).forEach(key => {
if (!obj[key]) {
delete obj[key]
}
})
return obj
}
// formats a route pattern into
function format ({ pathname, query }) {
query = Object.assign({}, query)
if (pathname === '/index') {
pathname = '/'
}
if (patterns[pathname]) {
const [...params] = patterns[pathname]
const pattern = params.pop()
pathname = pattern(query)
params.forEach(param => {
pathname = pathname.replace(`:${param}`, query[param])
delete query[param]
})
}
const q = qs.stringify(query)
return pathname + (q ? `?${q}` : '')
}
function link ({ pathname, query }, nextQuery, nextPathname) {
const q = clean(Object.assign({}, query, nextQuery))
const href = { pathname: nextPathname || pathname, query: q }
const as = format(href)
return { href, as }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.