Skip to content

Commit

Permalink
refactor: only compile rewrite rules once (#2018)
Browse files Browse the repository at this point in the history
  • Loading branch information
CHOYSEN authored Mar 8, 2023
1 parent 70ba404 commit bed31d0
Showing 1 changed file with 23 additions and 23 deletions.
46 changes: 23 additions & 23 deletions src/node/plugins/rewritesPlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,31 +6,31 @@ export function resolveRewrites(
pages: string[],
userRewrites: UserConfig['rewrites']
) {
const rewriteEntries = Object.entries(userRewrites || {})
const rewrites = rewriteEntries.length
? Object.fromEntries(
pages
.map((src) => {
for (const [from, to] of rewriteEntries) {
const dest = rewrite(src, from, to)
if (dest) return [src, dest]
}
})
.filter((e) => e != null) as [string, string][]
)
: {}
return {
map: rewrites,
inv: Object.fromEntries(Object.entries(rewrites).map((a) => a.reverse()))
const rewriteRules = Object.entries(userRewrites || {}).map(([from, to]) => ({
toPath: compile(to),
matchUrl: match(from)
}))

const pageToRewrite: Record<string, string> = {}
const rewriteToPage: Record<string, string> = {}
if (rewriteRules.length) {
for (const page of pages) {
for (const { matchUrl, toPath } of rewriteRules) {
const res = matchUrl(page)
if (res) {
const dest = toPath(res.params)
pageToRewrite[page] = dest
rewriteToPage[dest] = page
break
}
}
}
}
}

function rewrite(src: string, from: string, to: string) {
const urlMatch = match(from)
const res = urlMatch(src)
if (!res) return false
const toPath = compile(to)
return toPath(res.params)
return {
map: pageToRewrite,
inv: rewriteToPage
}
}

export const rewritesPlugin = (config: SiteConfig): Plugin => {
Expand Down

0 comments on commit bed31d0

Please sign in to comment.