Skip to content

feat: hono bff #6937

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Apr 21, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .changeset/dirty-eels-refuse.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
'@modern-js/create-request': patch
'@modern-js/plugin-express': patch
'@modern-js/plugin-koa': patch
'@modern-js/plugin-bff': patch
'@modern-js/server-core': patch
---

feat: bff supports hono runtime framework
feat: bff 支持 hono 运行时框架
9 changes: 9 additions & 0 deletions .changeset/new-wasps-accept.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
'@modern-js/plugin-express': patch
'@modern-js/app-tools': patch
'@modern-js/types': patch
'@modern-js/server-core': patch
---

refactor: avoid only one of "req" and "request" has a request body
refactor: 避免 req 和 request 只有一个有请求体
5 changes: 5 additions & 0 deletions packages/cli/core/src/types/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,4 +83,9 @@ export interface IAppContext {
* @private
*/
partialsByEntrypoint?: Record<string, HtmlPartials>;
/**
* Identification for bff runtime framework
* @private
*/
bffRuntimeFramework?: string;
}
13 changes: 12 additions & 1 deletion packages/cli/plugin-bff/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,11 @@
"jsnext:source": "./src/loader.ts",
"default": "./dist/cjs/loader.js"
},
"./hono": {
"types": "./dist/types/runtime/hono/index.d.ts",
"jsnext:source": "./src/runtime/hono/index.ts",
"default": "./dist/cjs/runtime/hono/index.js"
},
"./runtime/create-request": {
"types": "./dist/types/create-request/index.d.ts",
"jsnext:source": "./src/runtime/create-request/index.ts",
Expand All @@ -59,6 +64,9 @@
"server": [
"./dist/types/server.d.ts"
],
"hono": [
"./dist/types/runtime/hono/index.d.ts"
],
"runtime/create-request": [
"./dist/types/runtime/create-request/index.d.ts"
]
Expand All @@ -78,6 +86,7 @@
"@modern-js/server-core": "workspace:*",
"@modern-js/server-utils": "workspace:*",
"@modern-js/utils": "workspace:*",
"type-is": "^1.6.18",
"@swc/helpers": "0.5.13"
},
"devDependencies": {
Expand All @@ -92,11 +101,13 @@
"@types/babel__core": "^7.20.5",
"@types/jest": "^29",
"@types/node": "^14",
"@types/type-is": "^1.6.3",
"jest": "^29",
"memfs": "^3.5.1",
"ts-jest": "^29.1.0",
"typescript": "^5",
"webpack": "^5.98.0"
"webpack": "^5.98.0",
"zod": "^3.22.3"
},
"sideEffects": false,
"publishConfig": {
Expand Down
16 changes: 14 additions & 2 deletions packages/cli/plugin-bff/src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import runtimeGenerator from './utils/runtimeGenerator';
const DEFAULT_API_PREFIX = '/api';
const TS_CONFIG_FILENAME = 'tsconfig.json';
const RUNTIME_CREATE_REQUEST = '@modern-js/plugin-bff/runtime/create-request';
const RUNTIME_HONO = '@modern-js/plugin-bff/hono';

export const bffPlugin = (): CliPlugin<AppTools> => ({
name: '@modern-js/plugin-bff',
Expand Down Expand Up @@ -125,8 +126,17 @@ export const bffPlugin = (): CliPlugin<AppTools> => ({
}
};

const isHono = () => {
const { bffRuntimeFramework } = api.useAppContext();
return bffRuntimeFramework === 'hono';
};

return {
config() {
const honoRuntimePath = isHono()
? { [RUNTIME_HONO]: RUNTIME_HONO }
: undefined;

return {
tools: {
bundlerChain: (chain, { CHAIN_ID, isServer }) => {
Expand Down Expand Up @@ -184,6 +194,9 @@ export const bffPlugin = (): CliPlugin<AppTools> => ({
source: {
moduleScopes: [`./${API_DIR}`, /create-request/],
},
output: {
externals: honoRuntimePath,
},
};
},
modifyServerRoutes({ routes }) {
Expand All @@ -207,7 +220,7 @@ export const bffPlugin = (): CliPlugin<AppTools> => ({
isSSR: false,
})) as ServerRoute[];

if (bff?.enableHandleWeb) {
if (!isHono() && bff?.enableHandleWeb) {
return {
routes: (
routes.map(route => {
Expand All @@ -227,7 +240,6 @@ export const bffPlugin = (): CliPlugin<AppTools> => ({
plugins.push({
name: '@modern-js/plugin-bff/server',
});

return { plugins };
},
async beforeDev() {
Expand Down
109 changes: 109 additions & 0 deletions packages/cli/plugin-bff/src/runtime/hono/adapter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
import type { APIHandlerInfo } from '@modern-js/bff-core';
import type {
Context,
MiddlewareHandler,
Next,
PluginAPI,
ServerMiddleware,
} from '@modern-js/server-core';
import { Hono } from '@modern-js/server-core';

import { isProd } from '@modern-js/utils';
import createHonoRoutes from '../../utils/createHonoRoutes';

const before = ['custom-server-hook', 'custom-server-middleware', 'render'];

interface MiddlewareOptions {
prefix: string;
enableHandleWeb?: boolean;
}

export class HonoAdapter {
apiMiddleware: ServerMiddleware[] = [];
apiServer: Hono | null = null;
api: PluginAPI;
isHono = true;
constructor(api: PluginAPI) {
this.api = api;
}

setHandlers = async () => {
if (!this.isHono) {
return;
}
const { apiHandlerInfos } = this.api.useAppContext();

const honoHandlers = createHonoRoutes(apiHandlerInfos as APIHandlerInfo[]);
this.apiMiddleware = honoHandlers.map(({ path, method, handler }) => ({
name: 'hono-bff-api',
path,
method,
handler,
order: 'post',
before,
}));
};

registerApiRoutes = async () => {
if (!this.isHono) {
return;
}
this.apiServer = new Hono();
this.apiMiddleware.forEach(({ path = '*', method = 'all', handler }) => {
const handlers = this.wrapInArray(handler);
this.apiServer?.[method](path, ...handlers);
});
};

registerMiddleware = async (options: MiddlewareOptions) => {
const { prefix } = options;

const { bffRuntimeFramework } = this.api.useAppContext();

if (bffRuntimeFramework !== 'hono') {
this.isHono = false;
return;
}

const { middlewares: globalMiddlewares } = this.api.useAppContext();

await this.setHandlers();

if (isProd()) {
globalMiddlewares.push(...this.apiMiddleware);
} else {
await this.registerApiRoutes();
/** api hot update */
const dynamicApiMiddleware: ServerMiddleware = {
name: 'dynamic-bff-handler',
path: `${prefix}/*`,
method: 'all',
order: 'post',
before,
handler: async (c: Context, next: Next) => {
if (this.apiServer) {
const response = await this.apiServer.fetch(
c.req as unknown as Request,
c.env,
);

if (response.status !== 404) {
return new Response(response.body, response);
}
}
await next();
},
};
globalMiddlewares.push(dynamicApiMiddleware);
}
};
wrapInArray(
handler: MiddlewareHandler[] | MiddlewareHandler,
): MiddlewareHandler[] {
if (Array.isArray(handler)) {
return handler;
} else {
return [handler];
}
}
}
3 changes: 3 additions & 0 deletions packages/cli/plugin-bff/src/runtime/hono/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export * from '@modern-js/bff-core';
export { useHonoContext } from '@modern-js/server-core';
export * from './operators';
64 changes: 64 additions & 0 deletions packages/cli/plugin-bff/src/runtime/hono/operators.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import type { Operator } from '@modern-js/bff-core';
import {
type Context,
type Next,
useHonoContext,
} from '@modern-js/server-core';

export type EndFunction = ((func: (res: Response) => void) => void) &
((data: unknown) => void);

type MaybeAsync<T> = T | Promise<T>;
type PipeFunction<T> = (
value: T,
end: EndFunction,
) => MaybeAsync<void> | MaybeAsync<T>;

export const Pipe = <T>(func: PipeFunction<T>): Operator<T> => {
return {
name: 'pipe',
async execute(executeHelper, next) {
const { inputs } = executeHelper;
const ctx = useHonoContext();
const { res } = ctx;
if (typeof func === 'function') {
let isPiped = true;
const end: EndFunction = value => {
isPiped = false;
if (typeof value === 'function') {
value(res);
return;
}
return value;
};
const output = await func(inputs, end);
if (!isPiped) {
if (output) {
return (executeHelper.result = output);
} else {
return;
}
}
executeHelper.inputs = output as T;
await next();
}
},
};
};

export type Pipe = typeof Pipe;

export const Middleware = (
middleware: (c: Context, next: Next) => void,
): Operator<void> => {
return {
name: 'middleware',
metadata(helper) {
const middlewares = helper.getMetadata('pipe') || [];
middlewares.push(middleware);
helper.setMetadata('middleware', middlewares);
},
};
};

export type Middleware = typeof Middleware;
15 changes: 14 additions & 1 deletion packages/cli/plugin-bff/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ import {
isWebOnly,
requireExistModule,
} from '@modern-js/utils';
import { isFunction } from '@modern-js/utils';
import { API_APP_NAME } from './constants';
import { HonoAdapter } from './runtime/hono/adapter';

type SF = (args: any) => void;
class Storage {
Expand All @@ -32,6 +34,9 @@ export default (): ServerPluginLegacy => ({
const transformAPI = createTransformAPI(storage);
let apiAppPath = '';
let apiRouter: ApiRouter;

const honoAdapter = new HonoAdapter(api);

return {
async prepare() {
const appContext = api.useAppContext();
Expand Down Expand Up @@ -83,7 +88,7 @@ export default (): ServerPluginLegacy => ({
);
}

if (handler) {
if (handler && isFunction(handler)) {
globalMiddlewares.push({
name: 'bind-bff',
handler: (c, next) => {
Expand All @@ -101,6 +106,11 @@ export default (): ServerPluginLegacy => ({
],
});
}

honoAdapter.registerMiddleware({
prefix,
enableHandleWeb,
});
},
async reset({ event }) {
storage.reset();
Expand All @@ -123,6 +133,9 @@ export default (): ServerPluginLegacy => ({
...appContext,
apiHandlerInfos,
});

await honoAdapter.setHandlers();
await honoAdapter.registerApiRoutes();
}
},

Expand Down
Loading