Skip to content

Commit

Permalink
feat(path-rewrite): add path rewrite feature
Browse files Browse the repository at this point in the history
  • Loading branch information
radyakaze committed Aug 12, 2024
1 parent 80b920d commit 8aa214b
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 12 deletions.
1 change: 1 addition & 0 deletions src/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ export interface ProxyParty {
baseUrl: string
target: string
handler?: DefineProxyPartyHandler
pathRewrite?: { [s: string]: string } | ((path: string) => string)
}

export const defineProxyParty = (proxies: ProxyParty[]) => proxies
33 changes: 21 additions & 12 deletions src/runtime/server/plugin.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,36 @@
import { consola } from 'consola'
import { defineEventHandler, getQuery, proxyRequest } from 'h3'
import { withQuery, joinURL } from 'ufo'
import type { ProxyParty } from '../../core'
import { rewritePath } from '../../utils/path-rewrite'
import { defineNitroPlugin } from '#imports'

// @ts-expect-error virtual file
import configs from '#nuxt-proxy-party-options'

export default defineNitroPlugin(async ({ router }) => {
try {
if (Array.isArray(configs)) {
configs.forEach((config) => {
const handler = defineEventHandler((event) => {
const path = event.context.params?._ ?? '/'
const proxyHandler = (config: ProxyParty) => {
return defineEventHandler((event) => {
const path = event.context.params?._ ?? '/'

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

if (config.handler && typeof config.handler === 'function') {
config.handler(event)
}
if (config.pathRewrite) {
url = rewritePath(config.pathRewrite, url)
}

return proxyRequest(event, url)
})
if (config.handler && typeof config.handler === 'function') {
config.handler(event)
}

return proxyRequest(event, url)
})
}

export default defineNitroPlugin(async ({ router }) => {
try {
if (Array.isArray(configs)) {
configs.forEach((config: ProxyParty) => {
const handler = proxyHandler(config)
router.use(config.baseUrl, handler)
router.use(`${config.baseUrl}/**`, handler)
})
Expand Down
17 changes: 17 additions & 0 deletions src/utils/path-rewrite.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import type { ProxyParty } from '../core'

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

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

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

0 comments on commit 8aa214b

Please sign in to comment.