Skip to content

Commit

Permalink
fix: fix path rewrite
Browse files Browse the repository at this point in the history
  • Loading branch information
radyakaze committed Aug 12, 2024
1 parent 28ea45e commit 4416037
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 14 deletions.
3 changes: 1 addition & 2 deletions src/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,11 @@ export default defineNuxtModule<ModuleOptions>({

let serverConfig = `export default []`

consola.start('Nuxt Proxy Party: Started')
try {
serverConfig = await readFile(serverConfigPath, 'utf8')
}
catch {
console.error('Nuxt Proxy Party: No server.config found')
consola.error('Nuxt Proxy Party: No server.config found')
}

config.virtual['#nuxt-proxy-party-options'] = serverConfig
Expand Down
12 changes: 6 additions & 6 deletions src/runtime/server/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,11 @@ import configs from '#nuxt-proxy-party-options'

const proxyHandler = (config: ProxyParty) => {
return defineEventHandler((event) => {
const path = event.context.params?._ ?? '/'
let path = '/' + withQuery(event.context.params?._ ?? '', getQuery(event))

let url = withQuery(joinURL(config.target, path), getQuery(event))
path = rewritePath(config.pathRewrite, path)

if (config.pathRewrite) {
url = rewritePath(config.pathRewrite, url)
}
const url = joinURL(config.target, path)

if (config.handler && typeof config.handler === 'function') {
config.handler(event)
Expand All @@ -29,6 +27,8 @@ const proxyHandler = (config: ProxyParty) => {
export default defineNitroPlugin(async ({ router }) => {
try {
if (Array.isArray(configs)) {
consola.start('Nuxt Proxy Party: Started')

configs.forEach((config: ProxyParty) => {
const handler = proxyHandler(config)
router.use(config.baseUrl, handler)
Expand All @@ -39,6 +39,6 @@ export default defineNitroPlugin(async ({ router }) => {
}
}
catch (e: unknown) {
consola.error('Nuxt Proxy Party', (e as Error).message)
consola.error(`Nuxt Proxy Party: ${(e as Error).message}`)
}
})
12 changes: 6 additions & 6 deletions src/runtime/utils/path-rewrite.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
import type { ProxyParty } from '../../core'

export const rewritePath = (pathRewrite: ProxyParty['pathRewrite'], url: string) => {
if (!pathRewrite) return url
export const rewritePath = (pathRewrite: ProxyParty['pathRewrite'] | undefined, path: string) => {
if (!pathRewrite) return path

if (typeof pathRewrite === 'function') {
return pathRewrite(url)
return pathRewrite(path)
}

for (const [pattern, replacement] of Object.entries(pathRewrite)) {
const regex = new RegExp(pattern)
if (regex.test(url)) {
return url.replace(regex, replacement)
if (regex.test(path)) {
return path.replace(regex, replacement)
}
}
return url
return path
}

0 comments on commit 4416037

Please sign in to comment.