Skip to content

Commit

Permalink
feat: default add session & bodyparser support for koa/express/faas (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
czy88840616 committed Dec 12, 2021
1 parent d23e4a4 commit cdaff31
Show file tree
Hide file tree
Showing 75 changed files with 1,648 additions and 157 deletions.
2 changes: 1 addition & 1 deletion packages-serverless/koa-layer/package.json
Expand Up @@ -16,7 +16,7 @@
"@midwayjs/serverless-fc-trigger": "^3.0.0-beta.9",
"@midwayjs/serverless-scf-starter": "^3.0.0-beta.9",
"@midwayjs/serverless-scf-trigger": "^3.0.0-beta.9",
"koa": "^2.13.0",
"koa": "^2.13.4",
"koa-bodyparser": "^4.3.0",
"koa-router": "^9.4.0",
"supertest": "^6.0.0"
Expand Down
2 changes: 1 addition & 1 deletion packages-serverless/static-layer/package.json
Expand Up @@ -14,7 +14,7 @@
"@midwayjs/serverless-fc-trigger": "^3.0.0-beta.9",
"@midwayjs/serverless-scf-starter": "^3.0.0-beta.9",
"@midwayjs/serverless-scf-trigger": "^3.0.0-beta.9",
"koa": "^2.13.0",
"koa": "^2.13.4",
"koa-static-cache": "^5.1.4",
"path-to-regexp": "^6.2.0",
"request": "^2.88.2",
Expand Down
3 changes: 1 addition & 2 deletions packages/core/package.json
Expand Up @@ -35,8 +35,7 @@
"@midwayjs/logger": "^3.0.0-beta.9",
"class-transformer": "^0.5.1",
"extend2": "^1.0.0",
"picomatch": "^2.2.2",
"reflect-metadata": "^0.1.13"
"picomatch": "^2.2.2"
},
"author": "Harry Chen <czy88840616@gmail.com>",
"repository": {
Expand Down
11 changes: 6 additions & 5 deletions packages/core/src/baseFramework.ts
Expand Up @@ -312,15 +312,16 @@ export abstract class BaseFramework<
return returnResult.result;
}) as any);
this.composeMiddleware = await this.middlewareService.compose(
this.middlewareManager
this.middlewareManager,
this.app
);
await this.filterManager.init(this.applicationContext);
}
if (lastMiddleware) {
return await this.middlewareService.compose([
this.composeMiddleware,
lastMiddleware,
]);
return await this.middlewareService.compose(
[this.composeMiddleware, lastMiddleware],
this.app
);
} else {
return this.composeMiddleware;
}
Expand Down
67 changes: 67 additions & 0 deletions packages/core/src/common/applicationManager.ts
@@ -0,0 +1,67 @@
import { IMidwayApplication, IMidwayFramework } from '../interface';
import { FrameworkType, Provide, Scope, ScopeEnum } from '@midwayjs/decorator';

@Provide()
@Scope(ScopeEnum.Singleton)
export class MidwayApplicationManager {
private globalFrameworkMap = new Map<
string,
IMidwayFramework<any, any, any>
>();

private globalFrameworkTypeMap = new WeakMap<
FrameworkType,
IMidwayFramework<any, any, any>
>();

public addFramework(namespace, framework: IMidwayFramework<any, any, any>) {
this.globalFrameworkMap.set(namespace, framework);
this.globalFrameworkTypeMap.set(framework.getFrameworkType(), framework);
}

public getFramework(namespaceOrFrameworkType: string | FrameworkType) {
if (typeof namespaceOrFrameworkType === 'string') {
if (this.globalFrameworkMap.has(namespaceOrFrameworkType)) {
return this.globalFrameworkMap.get(namespaceOrFrameworkType);
}
} else {
if (this.globalFrameworkTypeMap.has(namespaceOrFrameworkType)) {
return this.globalFrameworkTypeMap.get(namespaceOrFrameworkType);
}
}
}

public getApplication(
namespaceOrFrameworkType: string | FrameworkType
): IMidwayApplication {
if (typeof namespaceOrFrameworkType === 'string') {
if (this.globalFrameworkMap.has(namespaceOrFrameworkType)) {
return this.globalFrameworkMap
.get(namespaceOrFrameworkType)
.getApplication();
}
} else {
if (this.globalFrameworkTypeMap.has(namespaceOrFrameworkType)) {
return this.globalFrameworkTypeMap
.get(namespaceOrFrameworkType)
.getApplication();
}
}
}

public getApplications(
namespaces: Array<string | FrameworkType>
): IMidwayApplication[] {
return namespaces
.map(namespace => {
return this.getApplication(namespace);
})
.filter(app => {
return !!app;
});
}

public getWebLikeApplication(): IMidwayApplication[] {
return this.getApplications(['express', 'koa', 'egg', 'faas']);
}
}
1 change: 1 addition & 0 deletions packages/core/src/index.ts
Expand Up @@ -37,6 +37,7 @@ export * from './common/webGenerator';
export * from './common/middlewareManager';
export * from './util/pathToRegexp';
export * from './common/filterManager';
export * from './common/applicationManager';
export * from './setup';
export * from './error';

Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/interface.ts
Expand Up @@ -346,7 +346,7 @@ export type NextFunction = () => Promise<any>;
* Common middleware definition
*/
export interface IMiddleware<CTX, R, N = unknown> {
resolve: () => FunctionMiddleware<CTX, R, N>;
resolve: (app?: IMidwayApplication) => FunctionMiddleware<CTX, R, N>;
match?: (ctx?: CTX) => boolean;
ignore?: (ctx?: CTX) => boolean;
}
Expand Down
28 changes: 15 additions & 13 deletions packages/core/src/service/frameworkService.ts
Expand Up @@ -3,7 +3,7 @@ import {
APPLICATION_KEY,
CONFIG_KEY,
FRAMEWORK_KEY,
FrameworkType,
getProviderUUId,
Init,
Inject,
listModule,
Expand All @@ -27,6 +27,7 @@ import { BaseFramework } from '../baseFramework';
import { MidwayPipelineService } from './pipelineService';
import { MidwayDecoratorService } from './decoratorService';
import { MidwayAspectService } from './aspectService';
import { MidwayApplicationManager } from '../common/applicationManager';
import * as util from 'util';
import { MidwayCommonError } from '../error';

Expand All @@ -47,18 +48,16 @@ export class MidwayFrameworkService {
@Inject()
decoratorService: MidwayDecoratorService;

@Inject()
applicationManager: MidwayApplicationManager;

constructor(
readonly applicationContext: IMidwayContainer,
readonly globalOptions
) {}

private mainFramework: IMidwayFramework<any, any, any>;

private globalFrameworkMap = new WeakMap<
FrameworkType,
IMidwayFramework<any, any, any>
>();

private globalFrameworkList: Array<IMidwayFramework<any, any, any>> = [];

@Init()
Expand Down Expand Up @@ -124,8 +123,11 @@ export class MidwayFrameworkService {
);
}
// app init
this.globalFrameworkMap.set(
frameworkInstance.getFrameworkType(),
const definition = this.applicationContext.registry.getDefinition(
getProviderUUId(frameworkClz)
);
this.applicationManager.addFramework(
definition?.namespace ?? frameworkInstance.getFrameworkName(),
frameworkInstance
);
this.globalFrameworkList.push(frameworkInstance);
Expand All @@ -136,11 +138,11 @@ export class MidwayFrameworkService {
APPLICATION_KEY,
(propertyName, mete) => {
if (mete.type) {
if (this.globalFrameworkMap.has(mete.type)) {
return this.globalFrameworkMap.get(mete.type).getApplication();
} else {
const framework = this.applicationManager.getApplication(mete.type);
if (!framework) {
throw new MidwayCommonError(`Framework ${mete.type} not Found`);
}
return framework;
} else {
return this.getMainApp();
}
Expand Down Expand Up @@ -177,8 +179,8 @@ export class MidwayFrameworkService {
return this.mainFramework;
}

public getFramework(type: MidwayFrameworkType) {
return this.globalFrameworkMap.get(type);
public getFramework(namespaceOrFrameworkType: string | MidwayFrameworkType) {
return this.applicationManager.getFramework(namespaceOrFrameworkType);
}

public async runFramework() {
Expand Down
4 changes: 3 additions & 1 deletion packages/core/src/service/middlewareService.ts
Expand Up @@ -4,6 +4,7 @@ import {
IMiddleware,
IMidwayContainer,
FunctionMiddleware,
IMidwayApplication,
} from '../interface';
import { MidwayCommonError, MidwayParameterError } from '../error';
import { isIncludeProperty, pathMatching } from '../util';
Expand All @@ -15,6 +16,7 @@ export class MidwayMiddlewareService<T, R, N = unknown> {

async compose(
middleware: Array<CommonMiddleware<T, R, N> | string>,
app: IMidwayApplication,
name?: string
) {
if (!Array.isArray(middleware)) {
Expand All @@ -37,7 +39,7 @@ export class MidwayMiddlewareService<T, R, N = unknown> {
IMiddleware<T, R, N>
>(fn as any);
if (classMiddleware) {
fn = classMiddleware.resolve();
fn = classMiddleware.resolve(app);
if (!classMiddleware.match && !classMiddleware.ignore) {
if (!fn.name) {
(fn as any)._name = classMiddleware.constructor.name;
Expand Down
2 changes: 2 additions & 0 deletions packages/core/src/setup.ts
Expand Up @@ -12,6 +12,7 @@ import {
MidwayLifeCycleService,
MidwayMiddlewareService,
MidwayDecoratorService,
MidwayApplicationManager,
safeRequire,
} from './';
import defaultConfig from './config/config.default';
Expand Down Expand Up @@ -67,6 +68,7 @@ export async function initializeGlobalApplicationContext(
applicationContext.bindClass(MidwayFrameworkService);
applicationContext.bindClass(MidwayMiddlewareService);
applicationContext.bindClass(MidwayLifeCycleService);
applicationContext.bindClass(MidwayApplicationManager);

// bind preload module
if (globalOptions.preloadModules && globalOptions.preloadModules.length) {
Expand Down
3 changes: 2 additions & 1 deletion packages/core/test/baseFramework.test.ts
Expand Up @@ -664,7 +664,8 @@ describe('/test/baseFramework.test.ts', () => {

// 再 compose
const composeMiddleware = await middlewareService.compose(
middlewareManager
middlewareManager,
{} as any
);

expect(await composeMiddleware({})).toEqual('hello world gogogo, zhangting');
Expand Down
36 changes: 36 additions & 0 deletions packages/core/test/common/applicationManager.test.ts
@@ -0,0 +1,36 @@
import { MidwayApplicationManager, BaseFramework } from '../../src';
import { MidwayFrameworkType } from '@midwayjs/decorator';

describe('test/common/applicationManager.test.ts', () => {
it('should test application manager', async () => {
const manager = new MidwayApplicationManager();

class CustomFramework1 extends BaseFramework<any, any, any> {
applicationInitialize(options): any {
this.app = {};
}

configure(options: any): any {
return {};
}

getFrameworkType() {
return MidwayFrameworkType.EMPTY;
}

run(): Promise<void> {
return Promise.resolve(undefined);
}
}

const framework = new CustomFramework1({} as any);
await framework.initialize();

manager.addFramework('test', framework);

expect(manager.getApplication('test')).toBeDefined();
expect(manager.getApplication(MidwayFrameworkType.EMPTY)).toBeDefined();
expect(manager.getApplication('xxxx')).toBeUndefined();
expect(manager.getApplications([MidwayFrameworkType.EMPTY, 'test', 'xxx']).length).toEqual(2);
});
});
8 changes: 4 additions & 4 deletions packages/core/test/service/middlewareService.test.ts
Expand Up @@ -347,7 +347,7 @@ describe('/test/services/middlewareService.test.ts', () => {
container.bindClass(TestMiddleware2);

const middlewareService = await container.getAsync(MidwayMiddlewareService, [container]);
const fn = await middlewareService.compose([TestMiddleware1, TestMiddleware2]);
const fn = await middlewareService.compose([TestMiddleware1, TestMiddleware2], {} as any);
const result = await fn({}, () => {
console.log('end');
});
Expand Down Expand Up @@ -381,8 +381,8 @@ describe('/test/services/middlewareService.test.ts', () => {
container.bindClass(TestMiddleware2);

const middlewareService = await container.getAsync(MidwayMiddlewareService, [container]);
const fn = await middlewareService.compose([TestMiddleware1]);
const fn2 = await middlewareService.compose([fn, TestMiddleware2]);
const fn = await middlewareService.compose([TestMiddleware1], {} as any);
const fn2 = await middlewareService.compose([fn, TestMiddleware2], {} as any);
const result = await fn2({});

expect(result).toEqual('hello world');
Expand Down Expand Up @@ -435,7 +435,7 @@ describe('/test/services/middlewareService.test.ts', () => {
container.bindClass(TestMiddleware3);

const middlewareService = await container.getAsync(MidwayMiddlewareService, [container]);
const fn = await middlewareService.compose([TestMiddleware, TestMiddleware1, TestMiddleware2, TestMiddleware3]);
const fn = await middlewareService.compose([TestMiddleware, TestMiddleware1, TestMiddleware2, TestMiddleware3], {} as any);
const result = await fn({body: ''}, () => {
console.log('end');
});
Expand Down

0 comments on commit cdaff31

Please sign in to comment.