-
-
Save KidkArolis/13027293d47ae460583642da9fb5257f to your computer and use it in GitHub Desktop.
5 Tips for Building a Next.js App (2)
This file contains 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 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