Skip to content

Instantly share code, notes, and snippets.

@KidkArolis
Created December 5, 2018 19:36
Show Gist options
  • Save KidkArolis/13027293d47ae460583642da9fb5257f to your computer and use it in GitHub Desktop.
Save KidkArolis/13027293d47ae460583642da9fb5257f to your computer and use it in GitHub Desktop.
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