Skip to content

Commit

Permalink
pass test/loader/egg_loader.test.ts
Browse files Browse the repository at this point in the history
  • Loading branch information
fengmk2 committed Jun 17, 2024
1 parent 98a77b3 commit 7bb2885
Show file tree
Hide file tree
Showing 8 changed files with 148 additions and 198 deletions.
22 changes: 11 additions & 11 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@eggjs/core",
"version": "6.0.0-beta.0",
"version": "6.0.0-beta.2",
"publishConfig": {
"access": "public"
},
Expand Down Expand Up @@ -36,6 +36,7 @@
"dependencies": {
"@eggjs/koa": "^2.18.2",
"@eggjs/router": "^3.0.5",
"@eggjs/utils": "^4.0.2",
"egg-logger": "^3.5.0",
"egg-path-matching": "^2.0.0",
"extend2": "^4.0.0",
Expand All @@ -50,26 +51,25 @@
},
"devDependencies": {
"@eggjs/tsconfig": "1",
"@types/js-yaml": "^4.0.9",
"@types/js-yaml": "4",
"@types/mocha": "10",
"@types/node": "20",
"@types/supertest": "^6.0.2",
"@types/supertest": "6",
"await-event": "2",
"coffee": "5",
"egg-bin": "6",
"egg-utils": "2",
"eslint": "8",
"eslint-config-egg": "13",
"gals": "^1.0.2",
"gals": "1",
"git-contributor": "2",
"js-yaml": "^3.13.1",
"js-yaml": "3",
"mm": "3",
"spy": "^1.0.0",
"supertest": "^4.0.2",
"spy": "1",
"supertest": "7",
"ts-node": "10",
"tshy": "^1.15.1",
"tshy-after": "^1.0.0",
"typescript": "^5.4.5",
"tshy": "1",
"tshy-after": "1",
"typescript": "5",
"urllib": "3"
},
"files": [
Expand Down
2 changes: 1 addition & 1 deletion src/lifecycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ export interface ILifecycleBoot {
beforeClose?(): Promise<void>;
}

export type BootImplClass<T = object> = (new(...args: any[]) => T) & ILifecycleBoot;
export type BootImplClass<T = ILifecycleBoot> = new(...args: any[]) => T;

export interface LifecycleOptions {
baseDir: string;
Expand Down
4 changes: 2 additions & 2 deletions src/loader/context_loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ export interface ContextLoaderOptions extends Omit<FileLoaderOptions, 'target'>
/** required inject */
inject: Record<string, any>;
/** property name defined to target */
property: string;
property: string | symbol;
/** determine the field name of inject object. */
fieldClass?: string;
}
Expand Down Expand Up @@ -86,7 +86,7 @@ export class ContextLoader extends FileLoader {
if (!ctx[CLASS_LOADER]) {
ctx[CLASS_LOADER] = new Map();
}
const classLoader: Map<string, ClassLoader> = ctx[CLASS_LOADER];
const classLoader: Map<string | symbol, ClassLoader> = ctx[CLASS_LOADER];
let instance = classLoader.get(property);
if (!instance) {
instance = getInstance(target, ctx);
Expand Down
35 changes: 17 additions & 18 deletions src/loader/egg_loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ export interface EggLoaderOptions {
env: string;
/** Application instance */
app: EggCore;
EggCoreClass: typeof EggCore;
EggCoreClass?: typeof EggCore;
/** the directory of application */
baseDir: string;
/** egg logger */
Expand Down Expand Up @@ -148,16 +148,12 @@ export class EggLoader {
* loader will find all directories from the prototype of Application,
* you should define `Symbol.for('egg#eggPath')` property.
*
* ```
* // lib/example.js
* const egg = require('egg');
* class ExampleApplication extends egg.Application {
* constructor(options) {
* super(options);
* }
*
* ```ts
* // src/example.ts
* import { Application } from 'egg';
* class ExampleApplication extends Application {
* get [Symbol.for('egg#eggPath')]() {
* return path.join(__dirname, '..');
* return baseDir;
* }
* }
* ```
Expand Down Expand Up @@ -367,20 +363,23 @@ export class EggLoader {
// stop the loop if
// - object extends Object
// - object extends EggCore
if (proto === Object.prototype || proto === EggCore.prototype) {
if (proto === Object.prototype || proto === EggCore?.prototype) {
break;
}

assert(proto.hasOwnProperty(Symbol.for('egg#eggPath')), 'Symbol.for(\'egg#eggPath\') is required on Application');
const eggPath = Reflect.get(proto, Symbol.for('egg#eggPath'));
assert(eggPath && typeof eggPath === 'string', 'Symbol.for(\'egg#eggPath\') should be string');
if (!eggPath) {
// if (EggCore) {
// throw new TypeError('Symbol.for(\'egg#eggPath\') is required on Application');
// }
continue;
}
assert(typeof eggPath === 'string', 'Symbol.for(\'egg#eggPath\') should be string');
assert(fs.existsSync(eggPath), `${eggPath} not exists`);
const realpath = fs.realpathSync(eggPath);
if (!eggPaths.includes(realpath)) {
eggPaths.unshift(realpath);
}
}

return eggPaths;
}

Expand Down Expand Up @@ -1493,12 +1492,12 @@ export class EggLoader {
* @param {Object} options - see {@link FileLoader}
* @since 1.0.0
*/
async loadToApp(directory: string | string[], property: string, options: FileLoaderOptions) {
async loadToApp(directory: string | string[], property: string | symbol, options?: FileLoaderOptions) {
const target = {};
Reflect.set(this.app, property, target);
options = {
...options,
directory: options.directory ?? directory,
directory: options?.directory ?? directory,
target,
inject: this.app,
};
Expand All @@ -1516,7 +1515,7 @@ export class EggLoader {
* @param {Object} options - see {@link ContextLoader}
* @since 1.0.0
*/
async loadToContext(directory: string | string[], property: string, options?: ContextLoaderOptions) {
async loadToContext(directory: string | string[], property: string | symbol, options?: ContextLoaderOptions) {
options = {
...options,
directory: options?.directory || directory,
Expand Down
58 changes: 3 additions & 55 deletions src/utils/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import { debuglog } from 'node:util';
import path from 'node:path';
import fs from 'node:fs';
import { pathToFileURL } from 'node:url';
import BuiltinModule from 'node:module';
import { createRequire } from 'node:module';
import { importResolve, importModule } from '@eggjs/utils';

const debug = debuglog('@eggjs/core:utils');

Expand All @@ -19,69 +18,21 @@ const extensions = (Module as any)._extensions;
const extensionNames = Object.keys(extensions).concat([ '.cjs', '.mjs' ]);
debug('Module extensions: %j', extensionNames);

let _customRequire: NodeRequire;
function getCustomRequire() {
if (!_customRequire && typeof require === 'undefined') {
_customRequire = createRequire(process.cwd());
// _customRequire = createRequire(import.meta.url);
}
return _customRequire;
}

export default {
deprecated(message: string) {
console.warn('[@eggjs/core:deprecated] %s', message);
},

extensions,

// async _importOrRequire(filepath: string) {
// // try import first
// let obj: any;
// try {
// obj = await import(filepath);
// } catch (err: any) {
// debug('await import error, use require instead, %s', err);
// // use custom require
// obj = getCustomRequire()(filepath);
// }
// return obj;
// },

async loadFile(filepath: string) {
try {
// if not js module, just return content buffer
const extname = path.extname(filepath);
if (extname && !extensionNames.includes(extname)) {
return fs.readFileSync(filepath);
}
let obj: any;
let isESM = false;
if (typeof require === 'function') {
// commonjs
obj = require(filepath);
debug('[loadFile] require %s => %o', filepath, obj);
if (obj && obj.__esModule) {
isESM = true;
}
} else {
// esm
debug('[loadFile] await import start: %s', filepath);
const fileUrl = pathToFileURL(filepath).toString();
obj = await import(fileUrl);
debug('[loadFile] await import end: %s => %o', filepath, obj);
isESM = true;
if (obj && typeof obj === 'object' && 'default' in obj) {
// default: { default: [Function (anonymous)] }
obj = obj.default;
}
}
if (!obj) return obj;
// it's es module, use default export
if (isESM && typeof obj === 'object') {
obj = 'default' in obj ? obj.default : obj;
}
debug('[loadFile] return %s => %o', filepath, obj);
const obj = await importModule(filepath, { importDefaultOnly: true });
return obj;
} catch (e: any) {
const err = new Error(`[@eggjs/core] load file: ${filepath}, error: ${e.message}`);
Expand All @@ -92,10 +43,7 @@ export default {
},

resolvePath(filepath: string, options?: { paths?: string[] }) {
if (typeof require !== 'undefined') {
return require.resolve(filepath, options);
}
return getCustomRequire().resolve(filepath, options);
return importResolve(filepath, options);
},

methods: [ 'head', 'options', 'get', 'put', 'patch', 'post', 'delete' ],
Expand Down
107 changes: 0 additions & 107 deletions test/loader/egg_loader.test.js

This file was deleted.

Loading

0 comments on commit 7bb2885

Please sign in to comment.