-
Notifications
You must be signed in to change notification settings - Fork 51
/
Copy pathindex.ts
85 lines (76 loc) · 2.29 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import chalk from 'chalk';
import http from 'http';
import { exit } from 'process';
import { Connect, Plugin, ViteDevServer } from 'vite';
import {
PLUGIN_NAME,
RequestAdapter,
RequestAdapterOption,
ViteConfig,
VitePluginNodeConfig
} from '..';
import { createDebugger } from '../utils';
import { ExpressHandler } from './express';
import { FastifyHandler } from './fastify';
import { KoaHandler } from './koa';
import { NestHandler } from './nest';
import { MarbleHandler } from './marble';
export const debugServer = createDebugger('vite:node-plugin:server');
export const SUPPORTED_FRAMEWORKS = {
express: ExpressHandler,
nest: NestHandler,
koa: KoaHandler,
fastify: FastifyHandler,
marble: MarbleHandler
};
export const getPluginConfig = (
server: ViteDevServer
): VitePluginNodeConfig => {
const plugin = server.config.plugins.find(
(p) => p.name === PLUGIN_NAME
) as Plugin;
if (!plugin) {
console.error('Please setup VitePluginNode in your vite.config.js first');
exit(1);
}
return (plugin.config!({}, { command: 'serve', mode: '' }) as ViteConfig)
.VitePluginNodeConfig;
};
const getRequestHandler = (
handler: RequestAdapterOption
): RequestAdapter | undefined => {
if (typeof handler === 'function') {
debugServer(chalk.dim`using custom server handler`);
return handler;
}
debugServer(chalk.dim`creating ${handler} node server`);
return SUPPORTED_FRAMEWORKS[handler] as RequestAdapter;
};
export const createMiddleware = (
server: ViteDevServer
): Connect.HandleFunction => {
const config = getPluginConfig(server);
const logger = server.config.logger;
const requestHandler = getRequestHandler(config.adapter);
if (!requestHandler) {
console.error('Failed to find a request handler');
process.exit(1);
}
return async function (
req: http.IncomingMessage,
res: http.ServerResponse
): Promise<void> {
const appModule = await server.ssrLoadModule(config.appPath);
let app = appModule[config.exportName!];
if (!app) {
logger.error(
`Failed to find a named export ${config.exportName} from ${config.appPath}`
);
process.exit(1);
} else {
// some app may be created with a function returning a promise
app = await app;
await requestHandler(app, req, res, server);
}
};
};