Skip to content

Commit

Permalink
Merge branch 'main' into feat/plugin-exist
Browse files Browse the repository at this point in the history
  • Loading branch information
caohuilin authored Jan 7, 2025
2 parents 0c55619 + fccc80d commit 24f7a62
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 3 deletions.
6 changes: 6 additions & 0 deletions .changeset/pretty-ravens-unite.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@modern-js/plugin-server': patch
---

fix: support unstable middleware hot reload
fix: 支持 unstable middleware 热更新
35 changes: 32 additions & 3 deletions packages/server/plugin-server/src/server.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import type { ServerPlugin } from '@modern-js/server-core';
import type { MiddlewareContext, NextFunction } from '@modern-js/types';
import type {
MiddlewareContext,
NextFunction,
UnstableMiddleware,
} from '@modern-js/types';
import { isProd, logger } from '@modern-js/utils';
import {
type Hook,
Expand All @@ -19,7 +23,7 @@ enum HOOKS {
class Storage {
public middlewares: Middleware[] = [];

public unstableMiddlewares: any[] = [];
public unstableMiddlewares: UnstableMiddleware[] = [];

public hooks: Record<string, Hook> = {};

Expand Down Expand Up @@ -142,7 +146,32 @@ export default (): ServerPlugin => ({
const { unstableMiddlewares } = storage;

if (unstableMiddlewares.length > 0) {
return unstableMiddlewares;
/**
* In prod mode, we just return unstableMiddlewares directly.
* In dev mode, we will return a new array with length of maxLen in the first time,
* The new Array will execute the storage.unstableMiddlewares[index] by index, when the middleware is not exist, we will execute next().
* It's the logic for hot reload, when unstableMiddlewares is changed, it will execute the new middleware.
*/
if (isProd()) {
return unstableMiddlewares;
} else {
const gap = 10;
const baseLen =
unstableMiddlewares.length < gap
? gap
: unstableMiddlewares.length;
const maxLen = baseLen + gap;
return new Array(maxLen).fill(0).map((_, index) => {
return (ctx, next) => {
const unstableMiddleware = storage.unstableMiddlewares[index];
if (unstableMiddleware) {
return unstableMiddleware(ctx, next);
} else {
return next();
}
};
});
}
}

factory = getFactory(storage);
Expand Down

0 comments on commit 24f7a62

Please sign in to comment.