Skip to content

Commit

Permalink
run pass the first test
Browse files Browse the repository at this point in the history
  • Loading branch information
fengmk2 committed Jun 16, 2024
1 parent e444095 commit ed50b9b
Show file tree
Hide file tree
Showing 40 changed files with 717 additions and 535 deletions.
8 changes: 3 additions & 5 deletions benchmark/middleware/app/controller/home.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
'use strict';

module.exports = {
* generator() {
async async() {
this.body = [];
},

async async() {
this.body = [];
async index() {
this.body = 'hello world';
},
};
10 changes: 0 additions & 10 deletions benchmark/middleware/app/middleware/generator.js

This file was deleted.

5 changes: 1 addition & 4 deletions benchmark/middleware/app/router.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,11 @@

module.exports = app => {
const asyncMiddlewares = [];
const generatorMiddlewares = [];
const transferMiddlewares = [];

for (let i = 0; i < 20; i++) {
asyncMiddlewares.push(app.middlewares.async());
generatorMiddlewares.push(app.middlewares.generator());
}

app.get('/', app.controller.home.index);
app.get('/async', ...asyncMiddlewares, 'home.async');
app.get('/generator', ...generatorMiddlewares, 'home.generator');
}
3 changes: 2 additions & 1 deletion benchmark/middleware/package.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
{
"name": "middleware"
"name": "middleware",
"type": "commonjs"
}
9 changes: 6 additions & 3 deletions benchmark/middleware/start.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,10 @@ const app = new EggApplication({
type: 'application',
});

app.loader.loadAll();
app.loader.loadAll().then(() => {
app.listen(7001);
console.log('server started at 7001');
}).catch(err => {
throw err;
});

app.listen(7001);
console.log('server started at 7001');
11 changes: 7 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,15 @@
"engines": {
"node": ">= 18.19.0"
},
"tnpm": {
"mode": "npm"
},
"description": "A core plugin framework based on koa",
"scripts": {
"lint": "eslint .",
"test": "npm run lint -- --fix && npm run test-local -- -p",
"lint": "eslint src test --ext ts",
"test": "npm run lint -- --fix && npm run test-local",
"test-local": "egg-bin test",
"ci": "npm run lint && egg-bin cov -p && npm run prepublishOnly",
"ci": "npm run lint && egg-bin cov && npm run prepublishOnly",
"contributor": "git-contributor",
"prepublishOnly": "tshy && tshy-after"
},
Expand All @@ -29,7 +32,7 @@
"homepage": "https://github.com/eggjs/egg-core#readme",
"dependencies": {
"@eggjs/koa": "^2.18.2",
"@eggjs/router": "^3.0.1",
"@eggjs/router": "^3.0.2",
"egg-logger": "^3.5.0",
"egg-path-matching": "^2.0.0",
"extend2": "^4.0.0",
Expand Down
2 changes: 2 additions & 0 deletions src/egg.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable prefer-spread */
import assert from 'node:assert';
import { debuglog } from 'node:util';
import is from 'is-type-of';
Expand Down Expand Up @@ -353,6 +354,7 @@ export class EggCore extends KoaApplication {
get(path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore;
get(name: string, path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore;
get(...args: any): EggCore {
debug('[router.get] args: %o', args);
this.router.get.apply(this.router, args);
return this;
}
Expand Down
4 changes: 2 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import utils from "./utils/index.js"
import utils from './utils/index.js';

export * from './egg.js';
export * from './loader/egg_loader.js'
export * from './loader/egg_loader.js';
export * from './base_context_class.js';
export { utils };
1 change: 1 addition & 0 deletions src/loader/context_loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ export class ContextLoader extends FileLoader {
// define ctx.service
Object.defineProperty(app.context, property, {
get() {
// eslint-disable-next-line @typescript-eslint/no-this-alias
const ctx = this;
// distinguish property cache,
// cache's lifecycle is the same with this context instance
Expand Down
53 changes: 28 additions & 25 deletions src/loader/egg_loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { extend } from 'extend2';
import { Request, Response, Context, Application, Next } from '@eggjs/koa';
import { pathMatching, type PathMatchingOptions } from 'egg-path-matching';
import { FULLPATH, FileLoader, FileLoaderOptions } from './file_loader.js';
import { ContextLoader, ContextLoaderOptions } from './context_loader.js'
import { ContextLoader, ContextLoaderOptions } from './context_loader.js';
import utils, { Fun } from '../utils/index.js';
import sequencify from '../utils/sequencify.js';
import { Timing } from '../utils/timing.js';
Expand Down Expand Up @@ -89,7 +89,7 @@ export interface EggDirInfo {
}

export class EggLoader {
#requiredCount: 0;
#requiredCount = 0;
readonly options: EggLoaderOptions;
readonly timing: Timing;
readonly pkg: Record<string, any>;
Expand Down Expand Up @@ -533,7 +533,7 @@ export class EggLoader {
}

if (customPlugins) {
const configPath = configPaths.join(' or ');
const configPath = configPaths.join(' or ');
for (const name in customPlugins) {
this.#normalizePluginConfig(customPlugins, name, configPath);
}
Expand Down Expand Up @@ -1290,6 +1290,10 @@ export class EggLoader {
if (!isClass(obj) && !isAsyncFunction(obj)) {
if (typeof obj === 'function') {
obj = obj(this.app);
debug('[loadController] after init(app) => %o, meta: %j', obj, opt);
if (isGeneratorFunction(obj)) {
throw new TypeError(`Support for generators was removed, fullpath: ${opt.path}`);
}
}
}
if (isClass(obj)) {
Expand All @@ -1300,17 +1304,15 @@ export class EggLoader {
if (isObject(obj)) {
return wrapObject(obj, opt.path);
}
if (isGeneratorFunction(obj)) {
throw new TypeError(`Support for generators was removed, fullpath: ${opt.path}`);
}
if (isAsyncFunction(obj)) {
return wrapObject({ 'module.exports': obj }, opt.path)['module.exports'];
}
return obj;
},
...opt,
}
};
await this.loadToApp(controllerBase, 'controller', opt as FileLoaderOptions);
debug('[loadController] app.controller => %o', this.app.controller);
this.options.logger.info('[@eggjs/core:egg_loader] Controller loaded: %s', controllerBase);
this.timing.end('Load Controller');
}
Expand All @@ -1331,9 +1333,8 @@ export class EggLoader {

/** start CustomLoader loader */
async loadCustomLoader() {
const loader = this;
assert(loader.config, 'should loadConfig first');
const customLoader = loader.config.customLoader || {};
assert(this.config, 'should loadConfig first');
const customLoader = this.config.customLoader || {};

for (const property of Object.keys(customLoader)) {
const loaderConfig = {
Expand All @@ -1345,7 +1346,7 @@ export class EggLoader {
if (loaderConfig.loadunit === true) {
directory = this.getLoadUnits().map(unit => path.join(unit.path, loaderConfig.directory));
} else {
directory = path.join(loader.appInfo.baseDir, loaderConfig.directory);
directory = path.join(this.appInfo.baseDir, loaderConfig.directory);
}
// don't override directory
delete loaderConfig.directory;
Expand All @@ -1356,25 +1357,25 @@ export class EggLoader {

switch (inject) {
case 'ctx': {
assert(!(property in loader.app.context), `customLoader should not override ctx.${property}`);
assert(!(property in this.app.context), `customLoader should not override ctx.${property}`);
const options = {
caseStyle: 'lower',
fieldClass: `${property}Classes`,
...loaderConfig,
};
loader.loadToContext(directory, property, options);
await this.loadToContext(directory, property, options);
break;
}
case 'app': {
assert(!(property in loader.app), `customLoader should not override app.${property}`);
assert(!(property in this.app), `customLoader should not override app.${property}`);
const options = {
caseStyle: 'lower',
initializer(Clazz: unknown) {
return isClass(Clazz) ? new Clazz(loader.app) : Clazz;
return isClass(Clazz) ? new Clazz(this.app) : Clazz;
},
...loaderConfig,
};
loader.loadToApp(directory, property, options);
await this.loadToApp(directory, property, options);
break;
}
default:
Expand Down Expand Up @@ -1651,26 +1652,28 @@ function wrapObject(obj: Record<string, any>, fullPath: string, prefix?: string)
const ret: Record<string, any> = {};
prefix = prefix ?? '';
for (const key of keys) {
if (typeof obj[key] === 'function') {
const names = getParamNames(obj[key]);
const item = obj[key];
if (typeof item === 'function') {
const names = getParamNames(item);
if (names[0] === 'next') {
throw new Error(`controller \`${prefix}${key}\` should not use next as argument from file ${fullPath}`);
}
ret[key] = objectFunctionToMiddleware(obj[key]);
ret[key] = objectFunctionToMiddleware(item);
ret[key][FULLPATH] = `${fullPath}#${prefix}${key}()`;
} else if (isObject(obj[key])) {
ret[key] = wrapObject(obj[key], fullPath, `${prefix}${key}.`);
} else if (isObject(item)) {
ret[key] = wrapObject(item, fullPath, `${prefix}${key}.`);
}
}
debug('[wrapObject] fullPath: %s, prefix: %s => %o', fullPath, prefix, ret);
return ret;
}

function objectFunctionToMiddleware(func: Fun) {
async function objectControllerMiddleware(this: EggCoreContext, ...args: any[]) {
if (!this.app.config.controller?.supportParams) {
args = [ this ];
async function objectControllerMiddleware(ctx: EggCoreContext, ...args: any[]) {
if (!ctx.app.config.controller?.supportParams) {
args = [ ctx ];
}
return await func.apply(this, args);
return await func.apply(ctx, args);
}
for (const key in func) {
Reflect.set(objectControllerMiddleware, key, Reflect.get(func, key));
Expand Down
21 changes: 12 additions & 9 deletions src/loader/file_loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ import { debuglog } from 'node:util';
import path from 'node:path';
import globby from 'globby';
import { isClass, isGeneratorFunction, isAsyncFunction, isPrimitive } from 'is-type-of';
import utils from '../utils/index.js';
import utils, { Fun } from '../utils/index.js';

const debug = debuglog('egg-core:loader');
const debug = debuglog('@eggjs/core:file_loader');

export const FULLPATH = Symbol('EGG_LOADER_ITEM_FULLPATH');
export const EXPORTS = Symbol('EGG_LOADER_ITEM_EXPORTS');
Expand Down Expand Up @@ -43,7 +43,7 @@ export interface FileLoaderOptions {
export interface FileLoaderParseItem {
fullpath: string;
properties: string[];
exports: object | Function;
exports: object | Fun;
}

/**
Expand Down Expand Up @@ -94,7 +94,7 @@ export class FileLoader {
const items = await this.parse();
const target = this.options.target;
for (const item of items) {
debug('loading item %j', item);
debug('loading item: %o', item);
// item { properties: [ 'a', 'b', 'c'], exports }
// => target.a.b.c = exports
item.properties.reduce((target, property, index) => {
Expand All @@ -113,7 +113,7 @@ export class FileLoader {
obj = target[property] || {};
}
target[property] = obj;
debug('loaded %s', properties);
debug('loaded item properties: %o => %o', properties, obj);
return obj;
}, target);
}
Expand Down Expand Up @@ -146,7 +146,7 @@ export class FileLoader {
* @return {Array} items
* @since 1.0.0
*/
async parse(): Promise<FileLoaderParseItem[]> {
protected async parse(): Promise<FileLoaderParseItem[]> {
let files = this.options.match;
if (!files) {
files = (process.env.EGG_TYPESCRIPT === 'true' && utils.extensions['.ts'])
Expand All @@ -170,7 +170,7 @@ export class FileLoader {

const filter = typeof this.options.filter === 'function' ? this.options.filter : null;
const items: FileLoaderParseItem[] = [];
debug('parsing %j', directories);
debug('parsing directories: %j', directories);
for (const directory of directories) {
const filepaths = globby.sync(files, { cwd: directory });
for (const filepath of filepaths) {
Expand All @@ -185,7 +185,9 @@ export class FileLoader {
const exports = await getExports(fullpath, this.options, pathName);

// ignore exports when it's null or false returned by filter function
if (exports == null || (filter && filter(exports) === false)) continue;
if (exports == null || (filter && filter(exports) === false)) {
continue;
}

// set properties of class
if (isClass(exports)) {
Expand All @@ -194,7 +196,7 @@ export class FileLoader {
}

items.push({ fullpath, properties, exports });
debug('parse %s, properties %j, export %j', fullpath, properties, exports);
debug('parse %s, properties %j, exports %o', fullpath, properties, exports);
}
}

Expand Down Expand Up @@ -222,6 +224,7 @@ async function getExports(fullpath: string, options: FileLoaderOptions, pathName
// process exports as you like
if (options.initializer) {
exports = options.initializer(exports, { path: fullpath, pathName });
debug('[getExports] after initializer => %o', exports);
}

if (isGeneratorFunction(exports)) {
Expand Down
Loading

0 comments on commit ed50b9b

Please sign in to comment.