Skip to content

Commit

Permalink
feat: support entry file in bootstrap (midwayjs#819)
Browse files Browse the repository at this point in the history
  • Loading branch information
czy88840616 authored Jan 27, 2021
1 parent ac33af2 commit 49a5ff6
Show file tree
Hide file tree
Showing 78 changed files with 601 additions and 422 deletions.
2 changes: 1 addition & 1 deletion .eslintrc.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"extends": "./node_modules/mwts/",
"ignorePatterns": ["node_modules", "dist", "test", "jest.config.js", "interface.ts"],
"ignorePatterns": ["node_modules", "dist", "test", "jest.config.js", "interface.ts", "app.js", "agent.js"],
"env": {
"jest": true
}
Expand Down
1 change: 1 addition & 0 deletions .github/workflows/nodejs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ jobs:
- run: npm install && npm install codecov
- run: npm run bootstrap
- run: npm run build --if-present
- run: npm run lint
- run: npm run cov
- name: Upload coverage to Codecov
uses: codecov/codecov-action@v1
Expand Down
4 changes: 2 additions & 2 deletions packages-serverless/faas-typings/typings/fc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ export namespace FC {
export type MNSEvent = string | MNSStreamEvent | MNSJSONEvent;

export interface SLSEvent {
parameter: object;
parameter: Record<string, unknown>;
source: {
endpoint: string;
projectName: string;
Expand Down Expand Up @@ -141,7 +141,7 @@ export namespace FC {
export interface APIGatewayResponse {
isBase64Encoded: boolean;
statusCode: number;
headers: object;
headers: Record<string, unknown>;
body: string;
}

Expand Down
12 changes: 6 additions & 6 deletions packages-serverless/faas-typings/typings/scf.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,23 +104,23 @@ export namespace SCF {
/**
* 记录实际请求的完整 Header 内容
*/
headers: object;
headers: Record<string, unknown>;
/**
* 记录实际请求的完整 Body 内容
*/
body: string;
/**
* 记录在 API 网关中配置过的 Path 参数以及实际取值
*/
pathParameters: object;
pathParameters: Record<string, unknown>;
/**
* 记录在 API 网关中配置过的 Query 参数以及实际取值
*/
queryStringParameters: object;
queryStringParameters: Record<string, unknown>;
/**
* 记录在 API 网关中配置过的 Header 参数以及实际取值
*/
headerParameters: object;
headerParameters: Record<string, unknown>;
stageVariables: {
stage: string;
};
Expand All @@ -131,14 +131,14 @@ export namespace SCF {
/**
* 请求地址的查询参数
*/
queryString: object;
queryString: Record<string, unknown>;
httpMethod: string;
}

export interface APIGatewayResponse {
isBase64Encoded: boolean;
statusCode: number;
headers: object;
headers: Record<string, unknown>;
body: string;
}

Expand Down
2 changes: 1 addition & 1 deletion packages-serverless/serverless-aws-starter/src/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export class AWSRuntime extends ServerlessLightRuntime {
if (handler.constructor.name !== 'AsyncFunction') {
throw new TypeError('Must be an AsyncFunction');
}
return (event: object, context?: AWSContext) => {
return (event = {}, context?: AWSContext) => {
if (isHttpEvent(event)) {
return this.wrapperWebInvoker(handler, event, context);
}
Expand Down
2 changes: 1 addition & 1 deletion packages-serverless/serverless-fc-starter/src/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ export class FCRuntime extends ServerlessLightRuntime {
if (isHTTPMode) {
req.getOriginContext = () => {
return context;
}
};
// http
// const rawBody = 'test';
// req.rawBody = rawBody;
Expand Down
2 changes: 1 addition & 1 deletion packages-serverless/serverless-scf-starter/src/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export class SCFRuntime extends ServerlessLightRuntime {
* @param handler
*/
asyncEvent(handler) {
return (event: object = {}, context = {} as SCF.RequestContext) => {
return (event = {}, context = {} as SCF.RequestContext) => {
if (isHttpEvent(event)) {
return this.wrapperWebInvoker(handler, event, context);
}
Expand Down
12 changes: 11 additions & 1 deletion packages/bootstrap/src/bootstrap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,16 @@ export class BootstrapStarter {

public async run() {
await Promise.all(this.getActions('run', {}));
if (global['MIDWAY_BOOTSTRAP_APP_SET']) {
// for test/dev
this.bootstrapItems.forEach(item => {
global['MIDWAY_BOOTSTRAP_APP_SET'].add({
framework: item,
starter: this,
});
});
global['MIDWAY_BOOTSTRAP_APP_READY'] = true;
}
}

public async stop() {
Expand Down Expand Up @@ -81,7 +91,7 @@ export class Bootstrap {
}
configuration.logger = this.logger;
} else {
this.logger = this.logger || configuration.logger as ILogger;
this.logger = this.logger || (configuration.logger as ILogger);
}
this.getStarter().configure(configuration);
return this;
Expand Down
9 changes: 9 additions & 0 deletions packages/bootstrap/test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,4 +152,13 @@ describe('/test/index.test.ts', () => {
expect(framework.getBaseDir()).toEqual(join(process.cwd(), 'dist'));
await Bootstrap.stop();
});

it('should test bootstrap run with mock', async () => {
global['MIDWAY_BOOTSTRAP_APP_SET'] = new Set();
const framework = new TestFrameworkUnit().configure({});
await Bootstrap.load(framework).run();
expect(global['MIDWAY_BOOTSTRAP_APP_SET'].size).toEqual(1);
await Bootstrap.stop();
global['MIDWAY_BOOTSTRAP_APP_SET'] = null;
});
});
15 changes: 0 additions & 15 deletions packages/c-mongoose/.gitignore

This file was deleted.

16 changes: 0 additions & 16 deletions packages/c-mongoose/.npmignore

This file was deleted.

13 changes: 0 additions & 13 deletions packages/c-mongoose/src/configuration.ts

This file was deleted.

4 changes: 0 additions & 4 deletions packages/c-mongoose/src/index.ts

This file was deleted.

50 changes: 31 additions & 19 deletions packages/core/src/baseFramework.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ import {
ILifeCycle,
IMidwayApplication,
IMidwayBootstrapOptions,
IMidwayContainer, IMidwayContext,
IMidwayContainer,
IMidwayContext,
IMidwayFramework,
MidwayFrameworkType,
MidwayProcessTypeEnum,
Expand All @@ -16,7 +17,12 @@ import {
listModule,
LOGGER_KEY,
} from '@midwayjs/decorator';
import { ILogger, loggers, LoggerOptions, IMidwayLogger } from '@midwayjs/logger';
import {
ILogger,
loggers,
LoggerOptions,
IMidwayLogger,
} from '@midwayjs/logger';
import { isAbsolute, join, dirname } from 'path';
import { createMidwayLogger, MidwayContextLogger } from './logger';
import { safeRequire } from './util';
Expand All @@ -36,7 +42,7 @@ function setupAppDir(baseDir: string) {
export abstract class BaseFramework<
APP extends IMidwayApplication<CTX>,
CTX extends IMidwayContext,
OPT extends IConfigurationOptions,
OPT extends IConfigurationOptions
> implements IMidwayFramework<APP, OPT> {
protected isTsMode = true;
protected baseDir: string;
Expand All @@ -46,13 +52,14 @@ export abstract class BaseFramework<
protected appLogger: ILogger;
public configurationOptions: OPT;
public app: APP;
protected pkg: object;
protected pkg: Record<string, unknown>;
protected defaultContext = {};
protected BaseContextLoggerClass: any;

public configure(options: OPT): BaseFramework<APP, CTX, OPT> {
this.configurationOptions = options;
this.BaseContextLoggerClass = options.ContextLoggerClass || this.getDefaultContextLoggerClass();
this.BaseContextLoggerClass =
options.ContextLoggerClass || this.getDefaultContextLoggerClass();
this.logger = options.logger;
this.appLogger = options.appLogger;
return this;
Expand Down Expand Up @@ -115,7 +122,9 @@ export abstract class BaseFramework<
protected async initializeLogger(options: IMidwayBootstrapOptions) {
if (!this.logger) {
this.logger = new Proxy(createMidwayLogger(this, 'coreLogger'), {});
(this.logger as IMidwayLogger).updateDefaultLabel(this.getFrameworkName());
(this.logger as IMidwayLogger).updateDefaultLabel(
this.getFrameworkName()
);
}
if (!this.appLogger) {
this.appLogger = createMidwayLogger(this, 'logger', {
Expand Down Expand Up @@ -244,8 +253,10 @@ export abstract class BaseFramework<
return this.baseDir;
}

protected defineApplicationProperties(applicationProperties: object = {}, whiteList = []) {
const self = this;
protected defineApplicationProperties(
applicationProperties = {},
whiteList: string[] = []
) {
const defaultApplicationProperties = {
getBaseDir: () => {
return this.baseDir;
Expand Down Expand Up @@ -295,30 +306,32 @@ export abstract class BaseFramework<
return this.getProjectName();
},

createAnonymousContext(extendCtx?: CTX) {
const ctx = extendCtx || Object.create(self.defaultContext);
createAnonymousContext: (extendCtx?: CTX) => {
const ctx = extendCtx || Object.create(this.defaultContext);
if (!ctx.startTime) {
ctx.startTime = Date.now();
}
if (!ctx.logger) {
ctx.logger = self.createContextLogger(ctx);
ctx.logger = this.createContextLogger(ctx);
}
if (!ctx.requestContext) {
ctx.requestContext = new MidwayRequestContainer(ctx, this.getApplicationContext());
ctx.requestContext = new MidwayRequestContainer(
ctx,
this.getApplicationContext()
);
ctx.requestContext.ready();
}
if (!ctx.getLogger) {
ctx.getLogger = (name) => {
return self.createContextLogger(ctx, name);
ctx.getLogger = name => {
return this.createContextLogger(ctx, name);
};
}
return ctx;
},

setContextLoggerClass(BaseContextLogger: any) {
return self.setContextLoggerClass(BaseContextLogger);
setContextLoggerClass: (BaseContextLogger: any) => {
return this.setContextLoggerClass(BaseContextLogger);
},

};
for (const method of whiteList) {
delete defaultApplicationProperties[method];
Expand Down Expand Up @@ -398,7 +411,7 @@ export abstract class BaseFramework<
}

public getProjectName() {
return this.pkg?.['name'] || '';
return (this.pkg?.['name'] as string) || '';
}

public getFrameworkName() {
Expand All @@ -408,5 +421,4 @@ export abstract class BaseFramework<
public getDefaultContextLoggerClass(): any {
return MidwayContextLogger;
}

}
4 changes: 2 additions & 2 deletions packages/core/src/context/configuration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export class ContainerConfiguration implements IContainerConfiguration {
packageName: string;
loadDirs: string[] = [];
loadModules: any[] = [];
importObjects: object = new Map();
importObjects = {};
// 新版本 configuration
newVersion = false;

Expand Down Expand Up @@ -89,7 +89,7 @@ export class ContainerConfiguration implements IContainerConfiguration {
}
}

addImportObjects(importObjects: object) {
addImportObjects(importObjects: Record<string, unknown>) {
if (importObjects) {
this.importObjects = importObjects;
}
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/context/midwayContainer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ export class MidwayContainer
private likeMainConfiguration: IContainerConfiguration[] = [];
protected configService: IConfigService;
protected environmentService: IEnvironmentService;
protected aspectMappingMap: WeakMap<object, Map<string, any[]>>;
protected aspectMappingMap: WeakMap<any, Map<string, any[]>>;
private aspectModuleSet: Set<any>;

/**
Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/definitions/properties.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ export class ObjectProperties implements IProperties {
}
}

putObject(props: object, needClone = false) {
putObject(props: Record<string, unknown>, needClone = false) {
if (needClone) {
const tmp = _.cloneDeep(props);
_.defaultsDeep(tmp, this.innerConfig);
Expand Down Expand Up @@ -86,7 +86,7 @@ export class ObjectProperties implements IProperties {
this.innerConfig = {};
}

toJSON(): object {
toJSON(): Record<string, unknown> {
return JSON.parse(JSON.stringify(this.innerConfig));
}

Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/definitions/resource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ export class Resource implements IResource {
return readFileSync(this.getPath());
}

getContentAsJSON(): object {
getContentAsJSON(): Record<string, unknown> {
if (!this.exists()) {
throw new Error(`${this.getPath()} not found!`);
}
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,7 @@ export interface IContainerConfiguration {
newVersion: boolean;
addLoadDir(dir: string);
addImports(imports: string[], baseDir?: string);
addImportObjects(importObjects: any[]);
addImportObjects(importObjects: Record<string, unknown>);
addImportConfigs(importConfigs: string[], baseDir: string);
load(packageName: string);
loadComponentObject(componentObject: any);
Expand Down
Loading

0 comments on commit 49a5ff6

Please sign in to comment.