Skip to content

Commit

Permalink
Merge pull request #6587 from clayrisser/clayrisser/conventional-midd…
Browse files Browse the repository at this point in the history
…leware-class

fix(core): detect conventional middleware class #6586
  • Loading branch information
kamilmysliwiec authored Mar 12, 2021
2 parents 82a1f8f + b5476ed commit 2cda45b
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 7 deletions.
15 changes: 12 additions & 3 deletions packages/core/middleware/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ export const mapToClass = <T extends Function | Type<any>>(
excludedRoutes: RouteInfoRegex[],
httpAdapter: HttpServer,
) => {
if (isClass(middleware)) {
if (isMiddlewareClass(middleware)) {
if (excludedRoutes.length <= 0) {
return middleware;
}
Expand Down Expand Up @@ -59,8 +59,17 @@ export const mapToClass = <T extends Function | Type<any>>(
);
};

export function isClass(middleware: any): middleware is Type<any> {
return middleware.toString().substring(0, 5) === 'class';
export function isMiddlewareClass(middleware: any): middleware is Type<any> {
const middlewareStr = middleware.toString();
if (middlewareStr.substring(0, 5) === 'class') {
return true;
}
const middlewareArr = middlewareStr.split(' ');
return (
middlewareArr[0] === 'function' &&
/[A-Z]/.test(middlewareArr[1]?.[0]) &&
typeof middleware.prototype?.use === 'function'
);
}

export function assignToken(metatype: Type<any>, token = uuid()): Type<any> {
Expand Down
8 changes: 4 additions & 4 deletions packages/core/test/middleware/utils.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import * as sinon from 'sinon';
import {
assignToken,
filterMiddleware,
isClass,
isMiddlewareClass,
isRouteExcluded,
mapToClass,
} from '../../middleware/utils';
Expand Down Expand Up @@ -63,15 +63,15 @@ describe('middleware utils', () => {
});
});
});
describe('isClass', () => {
describe('isMiddlewareClass', () => {
describe('when middleware is a class', () => {
it('should returns true', () => {
expect(isClass(Test)).to.be.true;
expect(isMiddlewareClass(Test)).to.be.true;
});
});
describe('when middleware is a function', () => {
it('should returns false', () => {
expect(isClass(fnMiddleware)).to.be.false;
expect(isMiddlewareClass(fnMiddleware)).to.be.false;
});
});
});
Expand Down

0 comments on commit 2cda45b

Please sign in to comment.