Skip to content

Commit

Permalink
fix: fix promise handler and proxyOptions
Browse files Browse the repository at this point in the history
  • Loading branch information
radyakaze committed Oct 7, 2024
1 parent 99a2910 commit 93f02d7
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 8 deletions.
4 changes: 2 additions & 2 deletions src/core.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { H3Event, ProxyOptions } from 'h3'

export type DefineProxyPartyHandler = (event: H3Event) => void
export type DefineProxyPartyHandler = (event: H3Event) => void | Promise<void>

export interface ProxyParty {
name?: string
Expand All @@ -9,7 +9,7 @@ export interface ProxyParty {
handler?: DefineProxyPartyHandler
pathRewrite?: { [s: string]: string } | ((path: string) => string)
enableLogger?: boolean
proxyOptions?: ProxyOptions | ((event: H3Event) => ProxyOptions)
proxyOptions?: ProxyOptions | ((event: H3Event) => ProxyOptions | Promise<ProxyOptions>)
}

export const defineProxyParty = (proxies: ProxyParty[]) => proxies
21 changes: 15 additions & 6 deletions src/runtime/server/plugin.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { defineEventHandler, getQuery, proxyRequest } from 'h3'
import { defineEventHandler, getQuery, proxyRequest, type ProxyOptions } from 'h3'
import { withQuery, joinURL } from 'ufo'
import type { ProxyParty } from '../../core'
import { rewritePath } from '../utils/path-rewrite'
Expand All @@ -9,24 +9,33 @@ import { defineNitroPlugin } from '#imports'
import configs from '#nuxt-proxy-party-options'

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

path = rewritePath(config.pathRewrite, path)

const url = joinURL(config.target, path)

if (config.handler && typeof config.handler === 'function') {
config.handler(event)
if (typeof config.handler === 'function') {
if (config.handler instanceof Promise) {
await config.handler(event)
}
else {
config.handler(event)
}
}

if (config.enableLogger) {
logger.success(`(${config.name || 'no name'})`, `Proxy path "${event.path}" accessed, forwarding to "${url}"`)
}

const options = typeof config.proxyOptions === 'function' ? config.proxyOptions(event) : config.proxyOptions
const options = typeof config.proxyOptions === 'function'
? config.proxyOptions instanceof Promise
? await config.proxyOptions(event)
: config.proxyOptions(event)
: config.proxyOptions

return proxyRequest(event, url, options)
return proxyRequest(event, url, options as ProxyOptions)
})
}

Expand Down

0 comments on commit 93f02d7

Please sign in to comment.