Skip to content

Commit

Permalink
remove ContextDelegation
Browse files Browse the repository at this point in the history
  • Loading branch information
fengmk2 committed Jan 2, 2025
1 parent f058c21 commit 8e3551c
Show file tree
Hide file tree
Showing 42 changed files with 456 additions and 302 deletions.
6 changes: 2 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,12 @@
"dependencies": {
"@eggjs/cluster": "^3.0.0",
"@eggjs/cookies": "^3.0.0",
"@eggjs/core": "^6.2.5",
"@eggjs/core": "^6.2.11",
"@eggjs/schedule": "^5.0.2",
"@eggjs/utils": "^4.1.5",
"@eggjs/watcher": "^4.0.1",
"circular-json-for-egg": "^1.0.0",
"cluster-client": "^3.7.0",
"delegates": "^1.0.0",
"egg-development": "^3.0.0",
"egg-errors": "^2.3.1",
"egg-i18n": "^2.1.1",
Expand Down Expand Up @@ -57,10 +56,9 @@
"@arethetypeswrong/cli": "^0.17.1",
"@eggjs/bin": "^7.0.0",
"@eggjs/koa": "^2.19.1",
"@eggjs/mock": "^6.0.3",
"@eggjs/mock": "^6.0.5",
"@eggjs/supertest": "^8.1.1",
"@eggjs/tsconfig": "1",
"@types/delegates": "^1.0.3",
"@types/koa-bodyparser": "^4.3.12",
"@types/mocha": "^10.0.7",
"@types/ms": "^0.7.34",
Expand Down
58 changes: 32 additions & 26 deletions src/app/extend/context.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import delegate from 'delegates';
import { assign } from 'utility';
import { now, diff } from 'performance-ms';
import {
utils, Context as EggCoreContext, Router,
type ContextDelegation as EggCoreContextDelegation,
} from '@eggjs/core';
import type { Cookies as ContextCookies } from '@eggjs/cookies';
import { EggLogger } from 'egg-logger';
Expand All @@ -12,8 +10,8 @@ import type {
HttpClientRequestURL, HttpClientRequestOptions, HttpClient,
} from '../../lib/core/httpclient.js';
import type { BaseContextClass } from '../../lib//core/base_context_class.js';
import Request from './request.js';
import Response from './response.js';
import type Request from './request.js';
import type Response from './response.js';
import type Helper from './helper.js';

import './context.types.js';
Expand All @@ -33,7 +31,9 @@ interface Cookies extends ContextCookies {
export default class Context extends EggCoreContext {
declare app: Application;
declare request: Request;
declare response: Response;
declare service: BaseContextClass;
declare proxy: any;

/**
* Request start time
Expand Down Expand Up @@ -230,7 +230,7 @@ export default class Context extends EggCoreContext {
* });
* ```
*/
runInBackground(scope: (ctx: ContextDelegation) => Promise<void>, taskName?: string): void {
runInBackground(scope: (ctx: Context) => Promise<void>, taskName?: string): void {
// try to use custom function name first
if (!taskName) {
taskName = Reflect.get(scope, '_name') || scope.name || utils.getCalleeFromStack(true);
Expand All @@ -243,7 +243,7 @@ export default class Context extends EggCoreContext {

// let plugins or frameworks to reuse _runInBackground in some cases.
// e.g.: https://github.com/eggjs/egg-mock/pull/78
async _runInBackground(scope: (ctx: ContextDelegation) => Promise<void>, taskName: string) {
async _runInBackground(scope: (ctx: Context) => Promise<void>, taskName: string) {
const startTime = now();
try {
await scope(this as any);
Expand All @@ -257,46 +257,52 @@ export default class Context extends EggCoreContext {
this.app.emit('error', err, this);
}
}
}

/**
* Context delegation.
*/

delegate(Context.prototype, 'request')
/**
* @member {Boolean} Context#acceptJSON
* @see Request#acceptJSON
* @since 1.0.0
*/
.getter('acceptJSON')
get acceptJSON(): boolean {
return this.request.acceptJSON;
}

get query(): Record<string, string> {
return this.request.query;
}

/**
* @member {Array} Context#queries
* @see Request#queries
* @since 1.0.0
*/
.getter('queries')
/**
* @member {Boolean} Context#accept
* @see Request#accept
* @since 1.0.0
*/
.getter('accept')
get queries(): Record<string, string[]> {
return this.request.queries;
}

/**
* @member {string} Context#ip
* @see Request#ip
* @since 1.0.0
*/
.access('ip');
get ip(): string {
return this.request.ip;
}

set ip(val: string) {
this.request.ip = val;
}

delegate(Context.prototype, 'response')
/**
* @member {Number} Context#realStatus
* @see Response#realStatus
* @since 1.0.0
*/
.access('realStatus');
get realStatus(): number {
return this.response.realStatus;
}

export type ContextDelegation = EggCoreContextDelegation & Context
& Pick<Request, 'acceptJSON' | 'queries' | 'accept' | 'ip'>
& Pick<Response, 'realStatus'>;
set realStatus(val: number) {
this.response.realStatus = val;
}
}
2 changes: 1 addition & 1 deletion src/app/extend/context.types.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import type {
Router,
} from '@eggjs/core';
import type { EggLogger } from 'egg-logger';
import type {
HttpClientRequestURL, HttpClientRequestOptions, HttpClient,
} from '../../lib/core/httpclient.js';
import type Helper from './helper.js';
import type { EggLogger } from 'egg-logger';

declare module '@eggjs/core' {
// add Context overrides types
Expand Down
9 changes: 7 additions & 2 deletions src/app/extend/request.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import querystring from 'node:querystring';
import { Request as EggCoreRequest } from '@eggjs/core';
import type { Application } from '../../lib/application.js';
import type { ContextDelegation } from './context.js';
import type Context from './context.js';
import Response from './response.js';

const QUERY_CACHE = Symbol('request query cache');
Expand All @@ -13,9 +13,14 @@ const RE_ARRAY_KEY = /[^\[\]]+\[\]$/;

export default class Request extends EggCoreRequest {
declare app: Application;
declare ctx: ContextDelegation;
declare ctx: Context;
declare response: Response;

/**
* Request body, parsed from koa-bodyparser or egg-multipart
*/
declare body: any;

/**
* Parse the "Host" header field host
* and support X-Forwarded-Host when a
Expand Down
10 changes: 10 additions & 0 deletions src/app/extend/request.types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
declare module '@eggjs/core' {
// add Request overrides types
interface Request {
body: any;
get acceptJSON(): boolean;
get query(): Record<string, string>;
set query(obj: Record<string, string>);
get queries(): Record<string, string[]>;
}
}
7 changes: 7 additions & 0 deletions src/app/extend/response.types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
declare module '@eggjs/core' {
// add Response overrides types
interface Response {
get realStatus(): number;
set realStatus(status: number);
}
}
4 changes: 2 additions & 2 deletions src/app/middleware/meta.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,15 @@
*/

import { performance } from 'node:perf_hooks';
import type { ContextDelegation, Next } from '../../lib/egg.js';
import type { Context, Next } from '../../lib/egg.js';

export interface MetaMiddlewareOptions {
enable: boolean;
logging: boolean;
}

export default (options: MetaMiddlewareOptions) => {
return async function meta(ctx: ContextDelegation, next: Next) {
return async function meta(ctx: Context, next: Next) {
if (options.logging) {
ctx.coreLogger.info('[meta] request started, host: %s, user-agent: %s',
ctx.host, ctx.header['user-agent']);
Expand Down
4 changes: 2 additions & 2 deletions src/app/middleware/notfound.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import type { Next, ContextDelegation } from '../../lib/egg.js';
import type { Next, Context } from '../../lib/egg.js';

export interface NotFoundMiddlewareOptions {
enable: boolean;
pageUrl: string;
}

export default (options: NotFoundMiddlewareOptions) => {
return async function notfound(ctx: ContextDelegation, next: Next) {
return async function notfound(ctx: Context, next: Next) {
await next();

if (ctx.status !== 404 || ctx.body) {
Expand Down
6 changes: 3 additions & 3 deletions src/app/middleware/site_file.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { readFile } from 'node:fs/promises';
import type { Next, ContextDelegation } from '../../lib/egg.js';
import type { Next, Context } from '../../lib/egg.js';

export type SiteFileContentFun = (ctx: ContextDelegation) => Promise<Buffer | string>;
export type SiteFileContentFun = (ctx: Context) => Promise<Buffer | string>;

export interface SiteFileMiddlewareOptions {
enable: boolean;
Expand All @@ -14,7 +14,7 @@ export interface SiteFileMiddlewareOptions {
const BUFFER_CACHE = Symbol('siteFile URL buffer cache');

export default (options: SiteFileMiddlewareOptions) => {
return async function siteFile(ctx: ContextDelegation, next: Next) {
return async function siteFile(ctx: Context, next: Next) {
if (ctx.method !== 'HEAD' && ctx.method !== 'GET') {
return next();
}
Expand Down
31 changes: 26 additions & 5 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,11 @@ import { startEgg } from './lib/start.js';
import Helper from './app/extend/helper.js';

// export extends
export { Helper };
export {
Helper,
// keep compatible with egg v3
Helper as IHelper,
};

// export types
export * from './lib/egg.js';
Expand All @@ -17,6 +21,15 @@ export * from './lib/start.js';
// export errors
export * from './lib/error/index.js';

// export loggers
export type {
LoggerLevel,
} from 'egg-logger';

// export httpClients
export * from './lib/core/httpclient.js';
export * from './lib/core/context_httpclient.js';

/**
* Start egg application with cluster mode
* @since 1.0.0
Expand All @@ -27,7 +40,9 @@ export * from '@eggjs/cluster';
* Start egg application with single process mode
* @since 1.0.0
*/
export const start = startEgg;
export {
startEgg as start,
};

/**
* @member {Application} Egg#Application
Expand Down Expand Up @@ -57,19 +72,25 @@ export { AppWorkerLoader, AgentWorkerLoader } from './lib/loader/index.js';
* @member {Controller} Egg#Controller
* @since 1.1.0
*/
export const Controller = BaseContextClass;
export {
BaseContextClass as Controller,
};

/**
* @member {Service} Egg#Service
* @since 1.1.0
*/
export const Service = BaseContextClass;
export {
BaseContextClass as Service,
};

/**
* @member {Subscription} Egg#Subscription
* @since 1.10.0
*/
export const Subscription = BaseContextClass;
export {
BaseContextClass as Subscription,
};

/**
* @member {BaseContextClass} Egg#BaseContextClass
Expand Down
6 changes: 3 additions & 3 deletions src/lib/application.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { isGeneratorFunction } from 'is-type-of';
import {
EggApplicationCore,
type EggApplicationCoreOptions,
type ContextDelegation,
type Context,
} from './egg.js';
import { AppWorkerLoader } from './loader/index.js';
import Helper from '../app/extend/helper.js';
Expand Down Expand Up @@ -223,7 +223,7 @@ export class Application extends EggApplicationCore {
* @see Context#runInBackground
* @param {Function} scope - the first args is an anonymous ctx
*/
runInBackground(scope: (ctx: ContextDelegation) => Promise<void>, req?: unknown) {
runInBackground(scope: (ctx: Context) => Promise<void>, req?: unknown) {
const ctx = this.createAnonymousContext(req);
if (!scope.name) {
Reflect.set(scope, '_name', eggUtils.getCalleeFromStack(true));
Expand All @@ -239,7 +239,7 @@ export class Application extends EggApplicationCore {
* @param {Function} scope - the first args is an anonymous ctx, scope should be async function
* @param {Request} [req] - if you want to mock request like querystring, you can pass an object to this function.
*/
async runInAnonymousContextScope(scope: (ctx: ContextDelegation) => Promise<void>, req?: unknown) {
async runInAnonymousContextScope(scope: (ctx: Context) => Promise<void>, req?: unknown) {
const ctx = this.createAnonymousContext(req);
if (!scope.name) {
Reflect.set(scope, '_name', eggUtils.getCalleeFromStack(true));
Expand Down
7 changes: 5 additions & 2 deletions src/lib/core/base_context_class.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { BaseContextClass as EggCoreBaseContextClass } from '@eggjs/core';
import type { ContextDelegation } from '../egg.js';
import type { Context, EggApplicationCore } from '../egg.js';
import { BaseContextLogger } from './base_context_logger.js';

/**
Expand All @@ -8,8 +8,11 @@ import { BaseContextLogger } from './base_context_logger.js';
* {@link Helper}, {@link Service} is extending it.
*/
export class BaseContextClass extends EggCoreBaseContextClass {
declare ctx: ContextDelegation;
[key: string | symbol]: any;
declare ctx: Context;
declare pathName?: string;
declare app: EggApplicationCore;
declare service: BaseContextClass;
#logger?: BaseContextLogger;

get logger() {
Expand Down
6 changes: 3 additions & 3 deletions src/lib/core/context_httpclient.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import type { ContextDelegation, EggApplicationCore } from '../egg.js';
import type { Context, EggApplicationCore } from '../egg.js';
import type {
HttpClientRequestURL, HttpClientRequestOptions,
} from './httpclient.js';

export class ContextHttpClient {
ctx: ContextDelegation;
ctx: Context;
app: EggApplicationCore;

constructor(ctx: ContextDelegation) {
constructor(ctx: Context) {
this.ctx = ctx;
this.app = ctx.app;
}
Expand Down
Loading

0 comments on commit 8e3551c

Please sign in to comment.