Skip to content

Commit

Permalink
fix: middleware disable in express (#2187)
Browse files Browse the repository at this point in the history
  • Loading branch information
czy88840616 committed Aug 1, 2022
1 parent ee7606e commit 8cad157
Show file tree
Hide file tree
Showing 11 changed files with 194 additions and 14 deletions.
18 changes: 18 additions & 0 deletions packages/core/src/common/middlewareManager.ts
Expand Up @@ -217,6 +217,24 @@ export class ContextMiddlewareManager<
}
}

public push(...items) {
items.forEach(item => {
if (typeof item !== 'string' && !this.getMiddlewareName(item)) {
item._name = 'anonymous';
}
});
return super.push(...items);
}

public unshift(...items): number {
items.forEach(item => {
if (typeof item !== 'string' && !this.getMiddlewareName(item)) {
item._name = 'anonymous';
}
});
return super.unshift(...items);
}

/**
* get middleware name list
*/
Expand Down
5 changes: 4 additions & 1 deletion packages/web-express/src/config/config.default.ts
Expand Up @@ -30,9 +30,12 @@ export const express = {
};

export const cookieParser: {
enable?: boolean;
secret?: string | string[];
options?: CookieOptions;
} = {};
} = {
enable: true,
};

export const bodyParser: {
enable?: boolean;
Expand Down
22 changes: 13 additions & 9 deletions packages/web-express/src/configuration.ts
Expand Up @@ -54,15 +54,19 @@ export class ExpressConfiguration {
this.configService.getConfiguration('keys');
const cookieParserConfig =
this.configService.getConfiguration('cookieParser');
// add cookie parser middleware
this.expressFramework
.getMiddleware()
.insertFirst(
cookieParser(
cookieParserConfig.secret ?? keys,
cookieParserConfig.options
)
);

if (cookieParserConfig.enable) {
// add cookie parser middleware
this.expressFramework
.getMiddleware()
.insertFirst(
cookieParser(
cookieParserConfig.secret ?? keys,
cookieParserConfig.options
)
);
}

// add body parser
const bodyparserConfig = this.configService.getConfiguration('bodyParser');
if (bodyparserConfig.enable) {
Expand Down
5 changes: 5 additions & 0 deletions packages/web-express/src/middlewareService.ts
Expand Up @@ -56,6 +56,11 @@ export class MidwayExpressMiddlewareService {
);
if (classMiddleware) {
fn = await classMiddleware.resolve(app);

if (!fn) {
// for middleware enabled
continue;
}
// wrap async middleware
fn = wrapAsyncHandler(fn);
if (!classMiddleware.match && !classMiddleware.ignore) {
Expand Down
@@ -0,0 +1,3 @@
{
"name": "ali-demo"
}
@@ -0,0 +1,21 @@
'use strict';

export const keys = 'key';

export const hello = {
a: 1,
b: 2,
d: [1, 2, 3],
};

export const bodyParser = {
enable: false,
}

export const session = {
enable: false,
}

export const cookieParser = {
enable: false,
}
@@ -0,0 +1,5 @@

exports.hello = {
b: 4,
c: 3,
};
@@ -0,0 +1,24 @@
import { Configuration, App } from '@midwayjs/decorator';
import { join } from 'path';
import { IMidwayExpressApplication, Context } from '../../../../src';

@Configuration({
imports: [
require('../../../../src')
],
importConfigs: [
join(__dirname, './config')
]
})
export class ContainerConfiguration {

@App()
app: IMidwayExpressApplication;

async onReady() {
this.app.use((req: Context, res, next) => {
console.log('invoke middleware in ready');
next();
});
}
}
@@ -0,0 +1,82 @@
import {
Controller,
Post,
Get,
Inject,
Query,
Body,
HttpCode,
Redirect,
SetHeader,
Logger,
Headers,
} from '@midwayjs/decorator';
import { UserService } from '../service/user';
import { Context } from '../../../../../src';
import { Response } from 'express';

@Controller('/api')
export class APIController {

@Inject()
ctx: Context;

@Inject()
req: Context;

@Inject()
res: Response;

@Logger()
logger;

@Inject('logger')
ctxLogger;

@Inject()
userService: UserService;

@Get('/set_header')
@SetHeader('bbb', 'aaa')
@SetHeader({
'ccc': 'ddd'
})
async homeSet() {
return 'bbb';
}

@Post()
async postData(@Body('bbbbb') bbbb) {
return bbbb;
}

@Get('/', { middleware: [] })
@HttpCode(201)
async home(@Query('name') name: string) {
this.ctx.logger.info('my home router');
this.ctxLogger.info('another ctx logger');
this.logger.warn('my home warn router')
return 'hello world,' + name;
}

@Get('/204')
async status204() {
// empty
}

@Get('/login')
@Redirect('/')
async redirect() {
}

@Get('/ctx-body')
async getCtxBody() {
this.res.send('ctx-body');
}

@Get('/header-upper')
async getHeaderWithUppercase(@Headers('X-ABC') abc) {
return abc;
}

}
@@ -0,0 +1,10 @@
import { Provide } from '@midwayjs/decorator';

@Provide()
export class UserService {
async hello(name) {
return {
name,
};
}
}
13 changes: 9 additions & 4 deletions packages/web-express/test/index.test.ts
@@ -1,5 +1,5 @@
import { closeApp, creatApp, createHttpRequest } from './utils';
import { IMidwayExpressApplication, MidwayExpressMiddlewareService} from '../src';
import { IMidwayExpressApplication, MidwayExpressMiddlewareService } from '../src';
import { createLightApp } from '@midwayjs/mock';

describe('/test/feature.test.ts', () => {
Expand All @@ -17,7 +17,7 @@ describe('/test/feature.test.ts', () => {
it('test setHeader decorator', async () => {
const result = await createHttpRequest(app)
.get('/api/set_header')
.query({ name: 'harry' });
.query({name: 'harry'});
expect(result.status).toEqual(200);
expect(result.text).toEqual('bbb');
expect(result.headers['bbb']).toEqual('aaa');
Expand All @@ -31,15 +31,15 @@ describe('/test/feature.test.ts', () => {
});

it('test get method with return value', async () => {
const result = await createHttpRequest(app).get('/api/').query({ name: 'harry' });
const result = await createHttpRequest(app).get('/api/').query({name: 'harry'});
expect(result.status).toBe(201);
expect(result.text).toBe('hello world,harry');
});

it('test post json data', async () => {
const result = await createHttpRequest(app).post('/api/').send({
bbbbb: 222,
})
});
expect(result.status).toBe(200);
expect(result.text).toBe('222');
});
Expand Down Expand Up @@ -300,5 +300,10 @@ describe('/test/feature.test.ts', () => {
await closeApp(app);
});

it('should disable default middleware', async () => {
const app = await creatApp('base-app-disable');
expect(app.getMiddleware().getNames()).toEqual(['session', 'anonymous']);
await closeApp(app);
});

});

0 comments on commit 8cad157

Please sign in to comment.