Skip to content

Commit

Permalink
feat: inject renderHandler to appContext & add default serverPlugins (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
GiveMe-A-Name authored Jul 30, 2024
1 parent c89066a commit 0e906a1
Show file tree
Hide file tree
Showing 11 changed files with 186 additions and 118 deletions.
8 changes: 8 additions & 0 deletions .changeset/hungry-frogs-bow.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
'@modern-js/prod-server': patch
'@modern-js/plugin-bff': patch
'@modern-js/server-core': patch
---

feat: inject renderHandler to appContext & add default serverPlugins
feat: 注入 renderHandler 到 appContext & 新增默认 serverPlugins
19 changes: 5 additions & 14 deletions packages/cli/plugin-bff/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
isWebOnly,
requireExistModule,
} from '@modern-js/utils';
import { getRenderHandler, type ServerPlugin } from '@modern-js/server-core';
import { type ServerPlugin } from '@modern-js/server-core';
import { ServerNodeMiddleware } from '@modern-js/server-core/node';
import { API_APP_NAME } from './constants';

Expand Down Expand Up @@ -35,7 +35,7 @@ export default (): ServerPlugin => ({
return {
async prepare() {
const appContext = api.useAppContext();
const { appDirectory, distDirectory } = appContext;
const { appDirectory, distDirectory, render } = appContext;
const root = isProd() ? distDirectory : appDirectory;
const apiPath = path.resolve(root || process.cwd(), API_DIR);
apiAppPath = path.resolve(apiPath, API_APP_NAME);
Expand All @@ -57,11 +57,8 @@ export default (): ServerPlugin => ({
const enableHandleWeb = config?.bff?.enableHandleWeb;
const httpMethodDecider = config?.bff?.httpMethodDecider;

const {
distDirectory: pwd,
routes,
middlewares: globalMiddlewares,
} = api.useAppContext();
const { distDirectory: pwd, middlewares: globalMiddlewares } =
api.useAppContext();

const webOnly = await isWebOnly();

Expand All @@ -74,13 +71,7 @@ export default (): ServerPlugin => ({
};
} else {
const runner = api.useHookRunners();
const renderHandler = enableHandleWeb
? await getRenderHandler({
pwd,
routes: routes || [],
config,
})
: null;
const renderHandler = enableHandleWeb ? render : null;
handler = await runner.prepareApiServer(
{
pwd,
Expand Down
34 changes: 34 additions & 0 deletions packages/server/core/src/plugins/default.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { Logger } from '@modern-js/types';
import type { ServerPlugin } from '../types';
import {
InjectRenderHandlerOptions,
injectRenderHandlerPlugin,
} from './render';
import {
initMonitorsPlugin,
injectloggerPluigin,
injectServerTiming,
} from './monitors';
import { processedByPlugin } from './processedBy';
import { logPlugin } from './log';
import { faviconPlugin } from './favicon';

export type CreateDefaultPluginsOptions = InjectRenderHandlerOptions & {
logger?: Logger;
};

export function createDefaultPlugins(
options: CreateDefaultPluginsOptions = {},
) {
const plugins: ServerPlugin[] = [
initMonitorsPlugin(),
injectRenderHandlerPlugin(options),
injectloggerPluigin(options.logger),
injectServerTiming(),
logPlugin(),
processedByPlugin(),
faviconPlugin(),
];

return plugins;
}
15 changes: 6 additions & 9 deletions packages/server/core/src/plugins/index.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,12 @@
export {
renderPlugin,
injectRenderHandlerPlugin,
type InjectRenderHandlerOptions,
getRenderHandler,
type RenderPluginOptions,
type GetRenderHandlerOptions,
} from './render';
export { faviconPlugin } from './favicon';
export { processedByPlugin } from './processedBy';
export { getLoaderCtx } from './customServer';
export { logPlugin } from './log';
export { injectServerTiming, injectloggerPluigin } from './monitors';
export {
initMonitorsPlugin,
injectServerTiming,
injectloggerPluigin,
} from './monitors';
createDefaultPlugins,
type CreateDefaultPluginsOptions,
} from './default';
7 changes: 4 additions & 3 deletions packages/server/core/src/plugins/monitors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,10 +89,11 @@ export const initMonitorsPlugin = (): ServerPlugin => ({
},
});

export const injectloggerPluigin = (logger: Logger): ServerPlugin => ({
export const injectloggerPluigin = (inputLogger?: Logger): ServerPlugin => ({
name: '@modern-js/inject-logger',

setup(api) {
const logger = inputLogger || console;
return {
prepare() {
const { middlewares } = api.useAppContext();
Expand Down Expand Up @@ -146,7 +147,7 @@ export const injectloggerPluigin = (logger: Logger): ServerPlugin => ({
},
});

export const injectServerTiming = (metaName = 'modern-js'): ServerPlugin => ({
export const injectServerTiming = (): ServerPlugin => ({
name: '@modern-js/inject-server-timing',

setup(api) {
Expand All @@ -158,7 +159,7 @@ export const injectServerTiming = (metaName = 'modern-js'): ServerPlugin => ({

return {
prepare() {
const { middlewares } = api.useAppContext();
const { middlewares, metaName } = api.useAppContext();

middlewares.push({
name: 'inject-server-timing',
Expand Down
70 changes: 9 additions & 61 deletions packages/server/core/src/plugins/render/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@ import {
Middleware,
ServerEnv,
Render,
UserConfig,
CacheConfig,
} from '../../types';
import { ServerNodeEnv } from '../../adapters/node/hono';
import { initReporter } from '../monitors';
Expand All @@ -17,27 +15,19 @@ import {
CustomServer,
getServerMidFromUnstableMid,
} from '../customServer';
import { createRender } from './render';

export interface RenderPluginOptions {
staticGenerate?: boolean;
cacheConfig?: CacheConfig;
}
export * from './inject';

export const renderPlugin = (
options: RenderPluginOptions = {},
): ServerPlugin => ({
export const renderPlugin = (): ServerPlugin => ({
name: '@modern-js/plugin-render',

setup(api) {
const { staticGenerate, cacheConfig } = options;

return {
async prepare() {
const {
middlewares,
routes,
metaName,
render,
distDirectory: pwd,
serverBase,
} = api.useAppContext();
Expand All @@ -56,15 +46,6 @@ export const renderPlugin = (

const pageRoutes = getPageRoutes(routes);

const render = await getRenderHandler({
pwd,
routes,
config,
metaName,
cacheConfig: config.render?.cache || cacheConfig,
staticGenerate,
});

for (const route of pageRoutes) {
const { urlPath: originUrlPath, entryName } = route;
const urlPath = originUrlPath.endsWith('/')
Expand Down Expand Up @@ -97,11 +78,12 @@ export const renderPlugin = (
handler: customServerMiddleware,
});

middlewares.push({
name: `render`,
path: urlPath,
handler: createRenderHandler(render),
});
render &&
middlewares.push({
name: `render`,
path: urlPath,
handler: createRenderHandler(render),
});
}
},
};
Expand Down Expand Up @@ -155,37 +137,3 @@ function createRenderHandler(
return c.body(body, status, headersData);
};
}

export interface GetRenderHandlerOptions {
pwd: string;
routes: ServerRoute[];
config: UserConfig;
cacheConfig?: CacheConfig;
staticGenerate?: boolean;
metaName?: string;
}

export async function getRenderHandler({
pwd,
routes,
config,
cacheConfig,
metaName,
staticGenerate,
}: GetRenderHandlerOptions): Promise<Render> {
const ssrConfig = config.server?.ssr;
const forceCSR = typeof ssrConfig === 'object' ? ssrConfig.forceCSR : false;

const render = createRender({
routes,
pwd,
config,
staticGenerate,
cacheConfig,
forceCSR,
nonce: config.security?.nonce,
metaName: metaName || 'modern-js',
});

return render;
}
74 changes: 74 additions & 0 deletions packages/server/core/src/plugins/render/inject.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import type {
CacheConfig,
GetRenderHandlerOptions,
Render,
ServerPlugin,
} from '../../types';
import { createRender } from './render';

export interface InjectRenderHandlerOptions {
staticGenerate?: boolean;
cacheConfig?: CacheConfig;
}

export const injectRenderHandlerPlugin = ({
staticGenerate,
cacheConfig,
}: InjectRenderHandlerOptions): ServerPlugin => ({
name: '@modern-js/plugin-inject-render',
setup(api) {
return {
async prepare() {
const { distDirectory: pwd, routes, metaName } = api.useAppContext();

const config = api.useConfigContext();

if (!routes) {
return;
}

const getRenderHandlerOptions: GetRenderHandlerOptions = {
pwd,
routes,
config,
metaName,
cacheConfig: config.render?.cache || cacheConfig,
staticGenerate,
};

const render = await getRenderHandler(getRenderHandlerOptions);

api.setAppContext({
...api.useAppContext(),
render,
getRenderOptions: getRenderHandlerOptions,
});
},
};
},
});

export async function getRenderHandler({
pwd,
routes,
config,
cacheConfig,
metaName,
staticGenerate,
}: GetRenderHandlerOptions): Promise<Render> {
const ssrConfig = config.server?.ssr;
const forceCSR = typeof ssrConfig === 'object' ? ssrConfig.forceCSR : false;

const render = createRender({
routes,
pwd,
config,
staticGenerate,
cacheConfig,
forceCSR,
nonce: config.security?.nonce,
metaName: metaName || 'modern-js',
});

return render;
}
12 changes: 12 additions & 0 deletions packages/server/core/src/types/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,10 +154,22 @@ type Middleware = {
order?: MiddlewareOrder;
};

export interface GetRenderHandlerOptions {
pwd: string;
routes: ServerRoute[];
config: UserConfig;
cacheConfig?: CacheConfig;
staticGenerate?: boolean;
metaName?: string;
}

declare module '@modern-js/types' {
export interface ISAppContext {
middlewares: Middleware[];
metaName: string;

getRenderOptions?: GetRenderHandlerOptions;
render?: Render;
routes?: ServerRoute[];
nodeServer?: NodeServer;
}
Expand Down
Loading

0 comments on commit 0e906a1

Please sign in to comment.