Skip to content

Commit 3d2bf55

Browse files
zllkjccaohuilin
andauthored
feat: add route info into unstable_middleware context (#6605)
Co-authored-by: Belinda Cao <caohuilin@bytedance.com>
1 parent b8d8520 commit 3d2bf55

File tree

8 files changed

+58
-6
lines changed

8 files changed

+58
-6
lines changed

.changeset/quick-cows-reply.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
---
2+
'@modern-js/plugin-server': patch
3+
'@modern-js/types': patch
4+
'@modern-js/server-core': patch
5+
---
6+
7+
feat: add route info into unstable_middleware context
8+
feat: 添加路由信息到 unstable_middleware 上下文中

packages/server/core/src/plugins/customServer/index.ts

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -218,7 +218,7 @@ export function getServerMidFromUnstableMid(
218218
): Array<Middleware<ServerNodeEnv & ServerEnv>> {
219219
return serverMiddleware.map(middleware => {
220220
return async (c, next) => {
221-
const context = await createMiddlewareContextFromHono(c as Context);
221+
const context = await createMiddlewareContextFromHono(c);
222222

223223
return middleware(context, next);
224224
};
@@ -230,7 +230,7 @@ function isRedirect(headers: Headers, code?: number) {
230230
}
231231

232232
async function createMiddlewareContextFromHono(
233-
c: Context<ServerNodeEnv>,
233+
c: Context<ServerNodeEnv & ServerEnv>,
234234
): Promise<UnstableMiddlewareContext> {
235235
const loaderContext = getLoaderCtx(c as Context);
236236

@@ -276,6 +276,10 @@ async function createMiddlewareContextFromHono(
276276
c.res = newRes;
277277
},
278278

279+
get route() {
280+
return c.get('route');
281+
},
282+
279283
get(key) {
280284
return loaderContext.get(key as string);
281285
},
@@ -295,3 +299,15 @@ async function createMiddlewareContextFromHono(
295299
redirect: c.redirect.bind(c),
296300
};
297301
}
302+
303+
export function injectRoute(route: {
304+
entryName: string;
305+
}): Middleware<ServerEnv> {
306+
return async (c, next) => {
307+
if (route && !c.get('route')) {
308+
c.set('route', route);
309+
}
310+
311+
await next();
312+
};
313+
}

packages/server/core/src/plugins/render/index.ts

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,11 @@ import type {
1010
ServerPlugin,
1111
} from '../../types';
1212
import { sortRoutes } from '../../utils';
13-
import { CustomServer, getServerMidFromUnstableMid } from '../customServer';
13+
import {
14+
CustomServer,
15+
getServerMidFromUnstableMid,
16+
injectRoute,
17+
} from '../customServer';
1418
import { initReporter } from '../monitors';
1519

1620
export * from './inject';
@@ -44,21 +48,26 @@ export const renderPlugin = (): ServerPlugin => ({
4448
const pageRoutes = getPageRoutes(routes);
4549

4650
for (const route of pageRoutes) {
47-
const { urlPath: originUrlPath, entryName } = route;
51+
const { urlPath: originUrlPath, entryName = MAIN_ENTRY_NAME } = route;
4852
const urlPath = originUrlPath.endsWith('/')
4953
? `${originUrlPath}*`
5054
: `${originUrlPath}/*`;
5155

5256
middlewares.push({
5357
name: 'init-reporter',
54-
handler: initReporter(entryName || MAIN_ENTRY_NAME),
58+
handler: initReporter(entryName),
5559
});
5660

5761
const customServerHookMiddleware = customServer.getHookMiddleware(
58-
entryName || 'main',
62+
entryName,
5963
routes,
6064
);
6165

66+
middlewares.push({
67+
name: 'inject-route-info',
68+
handler: injectRoute({ entryName }),
69+
});
70+
6271
middlewares.push({
6372
name: 'custom-server-hook',
6473
path: urlPath,

packages/server/core/src/types/server.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,11 @@ type ServerVariables = {
7070
* Custom by ssrRuntime.
7171
*/
7272
locals?: Record<string, any>;
73+
74+
/**
75+
* The current matched route, now only expose entryName field.
76+
*/
77+
route: Required<Pick<ServerRoute, 'entryName'>>;
7378
};
7479

7580
export type ServerEnv = {

packages/server/plugin-server/src/server.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,7 @@ export default (): ServerPlugin => ({
8585
const pwd = isProd() ? distDirectory : appDirectory;
8686

8787
const loadMod = async () => {
88+
// TODO:future, Modern.js removes the Hook concept, and `_middleware` file conventions can also be removed
8889
const { middleware: unstableMiddleware } = await loadMiddleware(pwd);
8990
const {
9091
defaultExports,

packages/toolkit/types/server/middleware.d.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import type { RequestPayload } from './context';
2+
import type { ServerRoute } from './route';
23

34
type Set<V extends Record<string>> = <Key extends keyof V>(
45
key: Key,
@@ -16,6 +17,7 @@ export type UnstableMiddlewareContext<
1617
> = {
1718
request: Request;
1819
response: Response;
20+
route: Required<Pick<ServerRoute, 'entryName'>>;
1921
get: Get<V & RequestPayload>;
2022
set: Set<V & RequestPayload>;
2123
header: (name: string, value: string, options?: { append?: boolean }) => void;

tests/integration/server-hook/new-middleware/server/index.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,10 +104,19 @@ function modifyRequest(): UnstableMiddleware {
104104
};
105105
}
106106

107+
function getRoute(): UnstableMiddleware {
108+
return async (c, next) => {
109+
c.response.headers.set('x-matched-route', c.route.entryName);
110+
111+
await next();
112+
};
113+
}
114+
107115
export const unstableMiddleware: UnstableMiddleware[] = [
108116
time(),
109117
modifyRequest(),
110118
injectRequestBody(),
111119
injectMessage(),
112120
auth() as unknown as UnstableMiddleware,
121+
getRoute(),
113122
];

tests/integration/server-hook/new-middleware/tests/index.test.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,8 @@ describe('test new middleware run correctly', () => {
5050
expect(body).toMatch(/lang="en"/);
5151

5252
expect(headers).toHaveProperty('x-custom-value', 'modern');
53+
54+
expect(headers).toHaveProperty('x-matched-route', 'main');
5355
});
5456

5557
test('should redirect corretly', async () => {

0 commit comments

Comments
 (0)