Skip to content

Commit

Permalink
feat: new server plugin (#5813)
Browse files Browse the repository at this point in the history
  • Loading branch information
GiveMe-A-Name authored Jun 19, 2024
1 parent c4018c2 commit a8d8f0c
Show file tree
Hide file tree
Showing 192 changed files with 3,186 additions and 2,417 deletions.
21 changes: 21 additions & 0 deletions .changeset/breezy-rings-jog.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
---
'@modern-js/plugin-data-loader': minor
'@modern-js/plugin-testing': minor
'@modern-js/plugin-polyfill': minor
'@modern-js/plugin-express': minor
'@modern-js/plugin-server': minor
'@modern-js/app-tools': minor
'@modern-js/prod-server': minor
'@modern-js/plugin-koa': minor
'@modern-js/uni-builder': minor
'@modern-js/plugin-bff': minor
'@modern-js/plugin-ssg': minor
'@modern-js/server': minor
'@modern-js/types': minor
'@modern-js/utils': minor
'@modern-js/server-core': minor
'@modern-js/core': minor
---

feat: support new server plugin & discard server plugin some hooks
feat: 支持新 server plugin & 减少 server plugin 钩子
5 changes: 1 addition & 4 deletions packages/cli/core/src/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import type {
CliPlugin,
UserConfig,
IAppContext,
InternalPlugins,
NormalizedConfig,
} from './types';

Expand Down Expand Up @@ -49,7 +48,6 @@ export const initAppContext = ({
runtimeConfigFile,
options,
serverConfigFile,
serverInternalPlugins,
}: {
appDirectory: string;
plugins: CliPlugin[];
Expand All @@ -63,7 +61,6 @@ export const initAppContext = ({
sharedDir?: string;
};
serverConfigFile: string;
serverInternalPlugins: InternalPlugins;
}): IAppContext => {
const {
metaName = 'modern-js',
Expand All @@ -78,7 +75,6 @@ export const initAppContext = ({
configFile,
runtimeConfigFile,
serverConfigFile,
serverInternalPlugins,
ip: address.ip(),
port: 0,
packageName: require(path.resolve(appDirectory, './package.json')).name,
Expand All @@ -88,6 +84,7 @@ export const initAppContext = ({
distDirectory: distDir,
sharedDirectory: path.resolve(appDirectory, sharedDir),
nodeModulesDirectory: path.resolve(appDirectory, './node_modules'),
serverPlugins: [],
internalDirectory: path.resolve(
appDirectory,
`./node_modules/.${metaName}`,
Expand Down
3 changes: 0 additions & 3 deletions packages/cli/core/src/createCli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import {
Command,
DEFAULT_RUNTIME_CONFIG,
DEFAULT_SERVER_CONFIG,
INTERNAL_SERVER_PLUGINS,
} from '@modern-js/utils';
import { initAppDir, initCommandsMap, createFileWatcher } from './utils';
import { loadPlugins } from './loadPlugins';
Expand Down Expand Up @@ -83,8 +82,6 @@ export const createCli = () => {
runtimeConfigFile: mergedOptions?.runtimeConfigFile || '',
options: mergedOptions?.options,
serverConfigFile: mergedOptions?.serverConfigFile || '',
serverInternalPlugins:
mergedOptions?.internalPlugins?.server || INTERNAL_SERVER_PLUGINS,
});

ConfigContext.set(loaded.config);
Expand Down
6 changes: 3 additions & 3 deletions packages/cli/core/src/types/context.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import {
Entrypoint,
InternalPlugins,
ServerRoute,
HtmlTemplates,
HtmlPartials,
ServerPlugin,
} from '@modern-js/types';
import type {
UniBuilderInstance,
Expand Down Expand Up @@ -37,8 +37,8 @@ export interface IAppContext {
runtimeConfigFile: string | false;
/** Path to the server configuration file */
serverConfigFile: string;
/** Currently registered server plugins */
serverInternalPlugins: InternalPlugins;
/** Server Plugins */
serverPlugins: ServerPlugin[];
/** IPv4 address of the current machine */
ip?: string;
/** Port number of the development server */
Expand Down
11 changes: 3 additions & 8 deletions packages/cli/core/tests/context.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
import path from 'path';
import {
DEFAULT_SERVER_CONFIG,
INTERNAL_SERVER_PLUGINS,
} from '@modern-js/utils';
import { DEFAULT_SERVER_CONFIG } from '@modern-js/utils';
import { initAppContext } from '../src/context';

describe('context', () => {
Expand All @@ -16,14 +13,12 @@ describe('context', () => {
configFile: false,
plugins: [],
serverConfigFile: DEFAULT_SERVER_CONFIG,
serverInternalPlugins: INTERNAL_SERVER_PLUGINS,
});

expect(appContext).toEqual({
appDirectory,
configFile: false,
serverConfigFile: DEFAULT_SERVER_CONFIG,
serverInternalPlugins: INTERNAL_SERVER_PLUGINS,
ip: expect.any(String),
port: 0,
packageName: expect.any(String),
Expand All @@ -36,6 +31,7 @@ describe('context', () => {
internalDirectory: expect.any(String),
plugins: [],
htmlTemplates: {},
serverPlugins: [],
serverRoutes: [],
entrypoints: [],
checkedEntries: [],
Expand Down Expand Up @@ -65,13 +61,11 @@ describe('context', () => {
configFile: false,
options: customOptions,
serverConfigFile: DEFAULT_SERVER_CONFIG,
serverInternalPlugins: INTERNAL_SERVER_PLUGINS,
});
expect(appContext).toEqual({
appDirectory,
configFile: false,
serverConfigFile: DEFAULT_SERVER_CONFIG,
serverInternalPlugins: INTERNAL_SERVER_PLUGINS,
ip: expect.any(String),
port: 0,
packageName: 'user-plugins',
Expand All @@ -85,6 +79,7 @@ describe('context', () => {
plugins: [],
htmlTemplates: {},
serverRoutes: [],
serverPlugins: [],
entrypoints: [],
checkedEntries: [],
apiOnly: false,
Expand Down
5 changes: 3 additions & 2 deletions packages/cli/plugin-bff/src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,10 +118,11 @@ export const bffPlugin = (): CliPlugin<AppTools> => ({
return { routes: routes.concat(apiServerRoutes) };
},

collectServerPlugins({ plugins }) {
_internalServerPlugins({ plugins }) {
plugins.push({
'@modern-js/plugin-bff': '@modern-js/plugin-bff/server',
name: '@modern-js/plugin-bff/server',
});

return { plugins };
},

Expand Down
93 changes: 80 additions & 13 deletions packages/cli/plugin-bff/src/server.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
import path from 'path';
import { ApiRouter } from '@modern-js/bff-core';
import { API_DIR, isProd, requireExistModule } from '@modern-js/utils';
import { type ServerPlugin } from '@modern-js/server-core';
import {
API_DIR,
isProd,
isWebOnly,
requireExistModule,
} from '@modern-js/utils';
import { getRenderHandler, type ServerPlugin } from '@modern-js/server-core';
import { ServerNodeMiddleware } from '@modern-js/server-core/node';
import { API_APP_NAME } from './constants';

type SF = (args: any) => void;
Expand All @@ -27,7 +33,7 @@ export default (): ServerPlugin => ({
let apiAppPath = '';
let apiRouter: ApiRouter;
return {
prepare() {
async prepare() {
const appContext = api.useAppContext();
const { appDirectory, distDirectory } = appContext;
const root = isProd() ? distDirectory : appDirectory;
Expand All @@ -44,8 +50,68 @@ export default (): ServerPlugin => ({
...appContext,
apiMiddlewares: middlewares,
});

/** bind api server */
const config = api.useConfigContext();
const prefix = config?.bff?.prefix || '/api';
const enableHandleWeb = config?.bff?.enableHandleWeb;
const httpMethodDecider = config?.bff?.httpMethodDecider;

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

const webOnly = await isWebOnly();

let handler: ServerNodeMiddleware;

if (webOnly) {
handler = async (c, next) => {
c.body('');
await next();
};
} else {
const runner = api.useHookRunners();
const renderHandler = enableHandleWeb
? await getRenderHandler({
pwd,
routes: routes || [],
config,
})
: null;
handler = await runner.prepareApiServer(
{
pwd,
prefix,
render: renderHandler,
httpMethodDecider,
},
{ onLast: () => null as any },
);
}

if (handler) {
globalMiddlewares.push({
name: 'bind-bff',
handler: (c, next) => {
if (!c.req.path.startsWith(prefix) && !enableHandleWeb) {
return next();
} else {
return handler(c, next);
}
},
order: 'post',
before: [
'custom-server-hook',
'custom-server-middleware',
'render',
],
});
}
},
reset() {
reset({ event }) {
storage.reset();
const appContext = api.useAppContext();
const newApiModule = requireExistModule(apiAppPath);
Expand All @@ -58,16 +124,17 @@ export default (): ServerPlugin => ({
...appContext,
apiMiddlewares: middlewares,
});

if (event.type === 'file-change') {
const apiHandlerInfos = apiRouter.getApiHandlers();
const appContext = api.useAppContext();
api.setAppContext({
...appContext,
apiHandlerInfos,
});
}
},
onApiChange(changes) {
const apiHandlerInfos = apiRouter.getApiHandlers();
const appContext = api.useAppContext();
api.setAppContext({
...appContext,
apiHandlerInfos,
});
return changes;
},

prepareApiServer(props, next) {
const { pwd, prefix, httpMethodDecider } = props;
const apiDir = path.resolve(pwd, API_DIR);
Expand Down
Loading

0 comments on commit a8d8f0c

Please sign in to comment.