Skip to content

Commit

Permalink
FileLoader
Browse files Browse the repository at this point in the history
  • Loading branch information
fengmk2 committed Jun 15, 2024
1 parent 3890c15 commit 9aaeaa4
Show file tree
Hide file tree
Showing 13 changed files with 344 additions and 304 deletions.
12 changes: 4 additions & 8 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,23 +30,20 @@
"dependencies": {
"@eggjs/koa": "^2.18.1",
"@eggjs/router": "^3.0.0",
"@types/depd": "^1.1.32",
"co": "^4.6.0",
"depd": "^2.0.0",
"egg-logger": "^3.5.0",
"egg-path-matching": "^1.1.0",
"extend2": "^1.0.1",
"extend2": "^4.0.0",
"get-ready": "^3.1.0",
"globby": "^11.0.2",
"is-type-of": "^2.1.0",
"koa-convert": "^1.2.0",
"node-homedir": "^2.0.0",
"ready-callback": "^4.0.0",
"tsconfig-paths": "^4.1.1",
"utility": "^2.1.0"
},
"devDependencies": {
"@eggjs/tsconfig": "1",
"@types/js-yaml": "^4.0.9",
"@types/mocha": "10",
"@types/node": "20",
"await-event": "2",
Expand All @@ -59,14 +56,13 @@
"git-contributor": "2",
"js-yaml": "^3.13.1",
"mm": "3",
"pedding": "^1.1.0",
"spy": "^1.0.0",
"supertest": "^4.0.2",
"ts-node": "10",
"urllib": "3",
"tshy": "^1.15.1",
"tshy-after": "^1.0.0",
"typescript": "^5.4.5"
"typescript": "^5.4.5",
"urllib": "3"
},
"publishConfig": {
"access": "public"
Expand Down
32 changes: 15 additions & 17 deletions src/egg.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
import assert from 'node:assert';
import fs from 'node:fs';
// import fs from 'node:fs';
import { debuglog } from 'node:util';
import is from 'is-type-of';
import KoaApplication, { type MiddlewareFunc } from '@eggjs/koa';
import { EggConsoleLogger } from 'egg-logger';
import { EggRouter as Router } from '@eggjs/router';
import type { ReadyFunctionArg } from 'get-ready';
import { BaseContextClass } from './utils/base_context_class';
import utils from './utils';
import { Timing } from './utils/timing';
import type { Fun } from './utils';
import { Lifecycle } from './lifecycle';
import type { EggLoader } from './loader/egg_loader';
import { BaseContextClass } from './utils/base_context_class.js';
import utils from './utils/index.js';
import { Timing } from './utils/timing.js';
import type { Fun } from './utils/index.js';
import { Lifecycle } from './lifecycle.js';
import { EggLoader, EggLoaderMixin } from './loader/egg_loader.js';

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

Expand All @@ -36,7 +36,7 @@ export class EggCore extends KoaApplication {
Controller: typeof BaseContextClass;
Service: typeof BaseContextClass;
lifecycle: Lifecycle;
loader: EggLoader;
loader: EggLoaderMixin;

/**
* @class
Expand All @@ -47,17 +47,15 @@ export class EggCore extends KoaApplication {
* @since 1.0.0
*/
constructor(options: Partial<EggCoreOptions> = {}) {
options.baseDir = options.baseDir || process.cwd();
options.type = options.type || 'application';

options.baseDir = options.baseDir ?? process.cwd();
options.type = options.type ?? 'application';
assert(typeof options.baseDir === 'string', 'options.baseDir required, and must be a string');
assert(fs.existsSync(options.baseDir), `Directory ${options.baseDir} not exists`);
assert(fs.statSync(options.baseDir).isDirectory(), `Directory ${options.baseDir} is not a directory`);
// assert(fs.existsSync(options.baseDir), `Directory ${options.baseDir} not exists`);
// assert(fs.statSync(options.baseDir).isDirectory(), `Directory ${options.baseDir} is not a directory`);
assert(options.type === 'application' || options.type === 'agent', 'options.type should be application or agent');
super();

this.timing = new Timing();

// cache deprecate object by file
this[DEPRECATE] = new Map();

Expand Down Expand Up @@ -137,8 +135,8 @@ export class EggCore extends KoaApplication {
plugins: options.plugins,
logger: this.console,
serverScope: options.serverScope,
env: options.env,
});
env: options.env ?? '',
}) as unknown as EggLoaderMixin;
}

/**
Expand Down Expand Up @@ -336,7 +334,7 @@ export class EggCore extends KoaApplication {
}

get [EGG_LOADER]() {
return require('./loader/egg_loader');
return EggLoader;
}
}

Expand Down
8 changes: 4 additions & 4 deletions src/lifecycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ import ReadyObject from 'get-ready';
import type { ReadyFunctionArg } from 'get-ready';
import { Ready } from 'ready-callback';
import { EggConsoleLogger } from 'egg-logger';
import utils from './utils';
import type { Fun } from './utils';
import type { EggCore } from './egg';
import utils from './utils/index.js';
import type { Fun } from './utils/index.js';
import type { EggCore } from './egg.js';

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

Expand Down Expand Up @@ -141,7 +141,7 @@ export class Lifecycle extends EventEmitter {
this.#bootHooks.push(BootClass);
}

addFunctionAsBootHook<T = EggApplication>(hook: (app: T) => void) {
addFunctionAsBootHook<T = EggCore>(hook: (app: T) => void) {
assert(this.#init === false, 'do not add hook when lifecycle has been initialized');
// app.js is exported as a function
// call this function in configDidLoad
Expand Down
42 changes: 24 additions & 18 deletions src/loader/base_loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { debuglog } from 'node:util';
import is from 'is-type-of';
import homedir from 'node-homedir';
import type { Logger } from 'egg-logger';
import utility from 'utility';
import { readJSONSync } from 'utility';
import FileLoader from './file_loader';
import ContextLoader from './context_loader';
import utils from '../utils';
Expand Down Expand Up @@ -65,6 +65,11 @@ export interface EggLoaderOptions {
plugins?: Record<string, PluginInfo>;
}

export interface EggDirInfo {
path: string;
type: 'app' | 'plugin' | 'framework';
}

export class BaseLoader {
#requiredCount: 0;
readonly options: EggLoaderOptions;
Expand All @@ -74,6 +79,7 @@ export class BaseLoader {
readonly serverEnv: string;
readonly serverScope: string;
readonly appInfo: EggAppInfo;
dirs?: EggDirInfo[];

/**
* @class
Expand All @@ -97,7 +103,7 @@ export class BaseLoader {
* @see {@link AppInfo#pkg}
* @since 1.0.0
*/
this.pkg = utility.readJSONSync(path.join(this.options.baseDir, 'package.json'));
this.pkg = readJSONSync(path.join(this.options.baseDir, 'package.json'));

// auto require('tsconfig-paths/register') on typescript app
// support env.EGG_TYPESCRIPT = true or { "egg": { "typescript": true } } on package.json
Expand Down Expand Up @@ -224,7 +230,7 @@ export class BaseLoader {
* @private
* @since 1.0.0
*/
getAppname() {
getAppname(): string {
if (this.pkg.name) {
debug('Loaded appname(%s) from package.json', this.pkg.name);
return this.pkg.name;
Expand All @@ -238,7 +244,7 @@ export class BaseLoader {
* @return {String} home directory
* @since 3.4.0
*/
getHomedir() {
getHomedir(): string {
// EGG_HOME for test
return process.env.EGG_HOME || homedir() || '/home/admin';
}
Expand Down Expand Up @@ -371,16 +377,16 @@ export class BaseLoader {
* ```
* @since 1.0.0
*/
loadFile(filepath, ...inject) {
filepath = filepath && this.resolveModule(filepath);
if (!filepath) {
loadFile(filepath: string, ...inject: Array<any>): any {
const realFilepath = filepath && this.resolveModule(filepath);
if (!realFilepath) {
return null;
}

// function(arg1, args, ...) {}
if (inject.length === 0) inject = [ this.app ];

let ret = this.requireFile(filepath);
let ret = this.requireFile(realFilepath);
if (is.function(ret) && !is.class(ret)) {
ret = ret(...inject);
}
Expand All @@ -392,12 +398,12 @@ export class BaseLoader {
* @return {Object} exports
* @private
*/
requireFile(filepath) {
requireFile(filepath: string): any {
const timingKey = `Require(${this.#requiredCount++}) ${utils.getResolvedFilename(filepath, this.options.baseDir)}`;
this.timing.start(timingKey);
const ret = utils.loadFile(filepath);
const moduleExports = utils.loadFile(filepath);
this.timing.end(timingKey);
return ret;
return moduleExports;
}

/**
Expand All @@ -415,16 +421,16 @@ export class BaseLoader {
* @return {Array} loadUnits
* @since 1.0.0
*/
getLoadUnits() {
getLoadUnits(): Array<any> {
if (this.dirs) {
return this.dirs;
}

const dirs = this.dirs = [];
this.dirs = [];

if (this.orderPlugins) {
for (const plugin of this.orderPlugins) {
dirs.push({
this.dirs.push({
path: plugin.path,
type: 'plugin',
});
Expand All @@ -433,20 +439,20 @@ export class BaseLoader {

// framework or egg path
for (const eggPath of this.eggPaths) {
dirs.push({
this.dirs.push({
path: eggPath,
type: 'framework',
});
}

// application
dirs.push({
this.dirs.push({
path: this.options.baseDir,
type: 'app',
});

debug('Loaded dirs %j', dirs);
return dirs;
debug('Loaded dirs %j', this.dirs);
return this.dirs;
}

/**
Expand Down
6 changes: 3 additions & 3 deletions src/loader/egg_loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -553,11 +553,11 @@ for (const loader of loaders) {
Object.assign(EggLoader.prototype, loader);
}

import { PluginLoader } from './mixin/plugin';
import ConfigLoader from './mixin/config';
import { PluginLoader } from './mixin/plugin.js';
import ConfigLoader from './mixin/config.js';

// https://www.typescriptlang.org/docs/handbook/mixins.html#alternative-pattern
export interface EggLoader extends PluginLoader, ConfigLoader {}
export interface EggLoaderMixin extends PluginLoader, ConfigLoader {}

// https://www.typescriptlang.org/docs/handbook/mixins.html
function applyMixins(derivedCtor: any, constructors: any[]) {
Expand Down
Loading

0 comments on commit 9aaeaa4

Please sign in to comment.