Skip to content

Commit

Permalink
fix: regexp for root path match (#2105)
Browse files Browse the repository at this point in the history
  • Loading branch information
czy88840616 committed Jul 12, 2022
1 parent 25e8448 commit 97ccc03
Show file tree
Hide file tree
Showing 26 changed files with 3,879 additions and 318 deletions.
14 changes: 10 additions & 4 deletions packages/bootstrap/src/bootstrap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,18 @@ export class BootstrapStarter {
return this.applicationContext;
}

public async run() {}
public async run() {
this.applicationContext = await this.init();
}

public async stop() {
await destroyGlobalApplicationContext(this.applicationContext);
}

public getApplicationContext() {
return this.applicationContext;
}

protected getBaseDir() {
if (this.globalOptions.baseDir) {
return this.globalOptions.baseDir;
Expand All @@ -62,7 +68,6 @@ export class Bootstrap {
private static starter: BootstrapStarter;
private static logger: IMidwayLogger;
private static configured = false;
private static applicationContext: IMidwayContainer;

/**
* set global configuration for midway
Expand Down Expand Up @@ -120,11 +125,11 @@ export class Bootstrap {
this.unhandledRejectionHandler = this.unhandledRejectionHandler.bind(this);
process.on('unhandledRejection', this.unhandledRejectionHandler);

this.applicationContext = await this.getStarter().init();
return this.getStarter()
.run()
.then(() => {
this.logger.info('[midway:bootstrap] current app started');
global['MIDWAY_BOOTSTRAP_APP_READY'] = true;
})
.catch(err => {
this.logger.error(err);
Expand All @@ -140,6 +145,7 @@ export class Bootstrap {
this.unhandledRejectionHandler
);
this.reset();
global['MIDWAY_BOOTSTRAP_APP_READY'] = false;
}

static reset() {
Expand Down Expand Up @@ -200,6 +206,6 @@ export class Bootstrap {
}

static getApplicationContext(): IMidwayContainer {
return this.applicationContext;
return this.getStarter().getApplicationContext();
}
}
1 change: 1 addition & 0 deletions packages/core/src/common/webGenerator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,7 @@ export abstract class WebControllerGenerator<
}

if (this.app.getFrameworkType() === MidwayFrameworkType.WEB_KOA) {
// egg use path-to-regexp v1 but koa use v6
if (typeof routeInfo.url === 'string' && /\*$/.test(routeInfo.url)) {
routeInfo.url = routeInfo.url.replace('*', '(.*)');
}
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/service/slsFunctionService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ export class MidwayServerlessFunctionService extends MidwayWebRouterService {
this.routes.set(prefix, []);
this.routesPriority.push({
prefix,
priority: -999,
priority: 0,
middleware: [],
routerOptions: {},
controllerId: undefined,
Expand Down
58 changes: 46 additions & 12 deletions packages/core/src/service/webRouterService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ import {
MidwayDuplicateRouteError,
} from '../error';
import * as util from 'util';
import { pathToRegexp } from '../util/pathToRegexp';
import { PathToRegexpUtil } from '../util/pathToRegexp';

const debug = util.debuglog('midway:debug');

Expand Down Expand Up @@ -58,6 +58,9 @@ export interface RouterInfo {
* router description
*/
description?: string;
/**
* @deprecated
*/
summary?: string;
/**
* router handler function key锛宖or IoC container load
Expand Down Expand Up @@ -104,10 +107,20 @@ export interface RouterInfo {
*/
functionMetadata?: any;

/**
* url with prefix
*/
fullUrl?: string;

/**
* pattern after path-regexp compile
*/
urlCompiledPattern?: RegExp;
fullUrlCompiledRegexp?: RegExp;

/**
* url after wildcard and can be path-to-regexp by path-to-regexp v6
*/
fullUrlFlattenString?: string;
}

export type DynamicRouterInfo = Omit<
Expand Down Expand Up @@ -331,12 +344,15 @@ export class MidwayWebRouterService {
routerInfoOption: DynamicRouterInfo
) {
const prefix = routerInfoOption.prefix || '';
routerInfoOption.requestMethod = (
routerInfoOption.requestMethod || 'GET'
).toUpperCase();

if (!this.routes.has(prefix)) {
this.routes.set(prefix, []);
this.routesPriority.push({
prefix,
priority: -999,
priority: 0,
middleware: [],
routerOptions: {},
controllerId: undefined,
Expand Down Expand Up @@ -448,10 +464,10 @@ export class MidwayWebRouterService {
this.includeCompileUrlPattern = true;
// attach match pattern function
for (const item of this.cachedFlattenRouteList) {
if (item.url) {
item.urlCompiledPattern = pathToRegexp(item.url, [], {
end: false,
});
if (item.fullUrlFlattenString) {
item.fullUrlCompiledRegexp = PathToRegexpUtil.toRegexp(
item.fullUrlFlattenString
);
}
}
}
Expand All @@ -469,9 +485,11 @@ export class MidwayWebRouterService {
this.includeCompileUrlPattern = true;
// attach match pattern function
for (const item of routeArr) {
item.urlCompiledPattern = pathToRegexp(item.url, [], {
end: false,
});
if (item.fullUrlFlattenString) {
item.fullUrlCompiledRegexp = PathToRegexpUtil.toRegexp(
item.fullUrlFlattenString
);
}
}
}
this.cachedFlattenRouteList = routeArr;
Expand All @@ -487,10 +505,10 @@ export class MidwayWebRouterService {
});
let matchedRouterInfo;
for (const item of routes) {
if (item.urlCompiledPattern) {
if (item.fullUrlCompiledRegexp) {
if (
method.toUpperCase() === item['requestMethod'].toUpperCase() &&
item.urlCompiledPattern.test(routerUrl)
item.fullUrlCompiledRegexp.test(routerUrl)
) {
matchedRouterInfo = item;
break;
Expand All @@ -517,6 +535,22 @@ export class MidwayWebRouterService {
`${routerInfo.handlerName}`
);
}
// format url
if (
!routerInfo.fullUrlFlattenString &&
routerInfo.url &&
typeof routerInfo.url === 'string'
) {
routerInfo.fullUrl = joinURLPath(prefix, routerInfo.url);
if (/\*$/.test(routerInfo.fullUrl)) {
routerInfo.fullUrlFlattenString = routerInfo.fullUrl.replace(
'*',
'(.*)'
);
} else {
routerInfo.fullUrlFlattenString = routerInfo.fullUrl;
}
}
prefixList.push(routerInfo);
}
}
4 changes: 2 additions & 2 deletions packages/core/src/util/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { dirname, resolve, sep, posix } from 'path';
import { readFileSync } from 'fs';
import { debuglog } from 'util';
import * as transformer from 'class-transformer';
import { pathToRegexp } from './pathToRegexp';
import { PathToRegexpUtil } from './pathToRegexp';
import { MidwayCommonError } from '../error';
import { FunctionMiddleware } from '../interface';

Expand Down Expand Up @@ -259,7 +259,7 @@ export function toPathMatch(pattern) {
return ctx => pattern;
}
if (typeof pattern === 'string') {
const reg = pathToRegexp(pattern, [], { end: false });
const reg = PathToRegexpUtil.toRegexp(pattern.replace('*', '(.*)'));
if (reg.global) reg.lastIndex = 0;
return ctx => reg.test(ctx.path);
}
Expand Down

0 comments on commit 97ccc03

Please sign in to comment.