Skip to content

Commit

Permalink
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(dev): proxy ws
Browse files Browse the repository at this point in the history
underfin committed Sep 29, 2020

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature.
1 parent 2893a41 commit 2829a68
Showing 2 changed files with 19 additions and 4 deletions.
4 changes: 2 additions & 2 deletions src/node/config.ts
Original file line number Diff line number Diff line change
@@ -23,10 +23,10 @@ import { ServerPlugin } from './server'
import { Resolver, supportedExts } from './resolver'
import { Transform, CustomBlockTransform } from './transform'
import { DepOptimizationOptions } from './optimizer'
import { IKoaProxiesOptions } from 'koa-proxies'
import { ServerOptions } from 'https'
import { lookupFile } from './utils'
import { Options as RollupTerserOptions } from 'rollup-plugin-terser'
import { ProxiesOptions } from './server/serverPluginProxy'

export type PreprocessLang = NonNullable<
SFCStyleCompileOptions['preprocessLang']
@@ -198,7 +198,7 @@ export interface ServerConfig extends SharedConfig {
* }
* ```
*/
proxy?: Record<string, string | IKoaProxiesOptions>
proxy?: Record<string, string | ProxiesOptions>
/**
* A plugin function that configures the dev server. Receives a server plugin
* context object just like the internal server plguins. Can also be an array
19 changes: 17 additions & 2 deletions src/node/server/serverPluginProxy.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import { ServerPlugin } from '.'
import { URL } from 'url'
import { IKoaProxiesOptions } from 'koa-proxies'

export const proxyPlugin: ServerPlugin = ({ app, config }) => {
export type ProxiesOptions = IKoaProxiesOptions & { ws: boolean }

export const proxyPlugin: ServerPlugin = ({ app, config, server }) => {
if (!config.proxy) {
return
}
@@ -12,8 +15,9 @@ export const proxyPlugin: ServerPlugin = ({ app, config }) => {
Object.keys(options).forEach((path) => {
let opts = options[path]
if (typeof opts === 'string') {
opts = { target: opts }
opts = { target: opts } as ProxiesOptions
}
if (opts.ws) return
opts.logs = (ctx, target) => {
debug(
`${ctx.req.method} ${(ctx.req as any).oldPath} proxy to -> ${new URL(
@@ -24,4 +28,15 @@ export const proxyPlugin: ServerPlugin = ({ app, config }) => {
}
app.use(proxy(path, opts))
})

server.on('upgrade', (req, socket, head) => {
if (req.headers['sec-websocket-protocol'] !== 'vite-hmr') {
for (const path in options) {
let opts = options[path]
if (typeof opts === 'object' && opts.ws) {
proxy.proxy.ws(req, socket, head, opts)
}
}
}
})
}

0 comments on commit 2829a68

Please sign in to comment.