egg
- Version 4.2.0
- Published
- 179 kB
- 42 dependencies
- MIT license
Install
npm i eggyarn add eggpnpm add eggOverview
A web application framework for Node.js
Index
Variables
Functions
Classes
EggApplicationCore
- agent
- application
- BaseContextClass
- BaseHookClass
- Boot
- cluster
- clusterWrapper()
- config
- ContextCookies
- ContextHttpClient
- ContextLogger
- Controller
- coreLogger
- createAnonymousContext()
- createContext()
- createHttpClient()
- ctxStorage
- curl()
- currentContext
- customEggPaths()
- dumpConfig()
- dumpConfigToObject()
- dumpManifest()
- dumpTiming()
- env
- getLogger()
- httpclient
- httpClient
- HttpClient
- HttpClientNext
- inspect()
- load()
- loadConfig()
- loader
- loadFinished
- logger
- loggers
- messenger
- options
- proxy
- runInAnonymousContextScope()
- Service
- snapshotDidDeserialize()
- snapshotWillSerialize()
- Subscription
- toJSON()
Interfaces
Type Aliases
Variables
variable Config
const Config: ObjectConstructor;variable EggAppConfig
const EggAppConfig: ObjectConstructor;Functions
function buildSnapshot
buildSnapshot: ( options?: Pick<StartEggOptions, 'framework' | 'baseDir' | 'env' | 'plugins'>) => Promise<void>;Build a V8 startup snapshot of an egg application.
Call this from the snapshot entry script passed to
node --snapshot-blob=snapshot.blob --build-snapshot snapshot_entry.js.It loads all metadata (plugins, configs, extensions, services, controllers, router, tegg modules), triggers snapshotWillSerialize hooks to clean up non-serializable resources (file handles, timers, process listeners), then registers a V8 deserialize callback to stash the app for later restore.
Example snapshot entry script:
import { buildSnapshot } from 'egg';await buildSnapshot({ baseDir: __dirname });Example restoring from snapshot:
import { restoreSnapshot } from 'egg';const app = await restoreSnapshot();// app is fully restored with resources recreated, ready for server creation
function createTransparentProxy
createTransparentProxy: <T extends object>( options: CreateTransparentProxyOptions<T>) => T;Create a Proxy that behaves like the real object, but remains transparent to monkeypatch libraries (e.g. defineProperty-based overrides like egg-mock's
mm()).- Lazily creates the real object on first access. - Allows overriding properties on the proxy target (overlay) — e.g. via
Object.defineProperty. - Delegates everything else to the real object.This is used to defer HttpClient construction so plugins can modify
config.httpclient.lookupafter the first access toapp.httpClientbut before any actual HTTP request is made.
function defineConfig
defineConfig: (config: PartialDeep<EggAppConfig>) => PartialDeep<EggAppConfig>;Define configuration with type safety
Example 1
import { defineConfig } from 'egg';export default defineConfig({keys: 'my-keys',middleware: []});
function defineConfigFactory
defineConfigFactory: (configFactory: EggConfigFactory) => EggConfigFactory;Define configuration factory function with type safety
Example 1
export default defineConfigFactory((appInfo): PartialEggConfig => ({keys: appInfo.name + '_keys',middleware: []}));
function definePluginFactory
definePluginFactory: (pluginMeta: EggPluginMeta) => EggPluginFactory;Define plugin factory with type safety
Example 1
import { definePluginFactory } from 'egg';export default definePluginFactory({name: 'my-plugin',enable: true,path: 'path/to/my-plugin',dependencies: ['watcher'],optionalDependencies: ['view'],env: ['local', 'unittest'],});
function restoreSnapshot
restoreSnapshot: () => Promise<Application>;Restore an egg application from a V8 startup snapshot.
Triggers the snapshotDidDeserialize lifecycle hooks to recreate non-serializable resources (messenger, loggers, process listeners) and resumes the lifecycle from configDidLoad through didReady.
Returns the fully restored Application instance with all metadata pre-loaded (plugins, configs, extensions, services, controllers, router).
function start
start: (options?: StartEggOptions) => Promise<SingleModeApplication>;Start egg with single process.
When
options.snapshotis true, loads application metadata for V8 startup snapshot construction. The lifecycle stops afterconfigWillLoad(no servers, timers, or connections) and skipsegg-readybroadcast.
function startEgg
startEgg: (options?: StartEggOptions) => Promise<SingleModeApplication>;Start egg with single process.
When
options.snapshotis true, loads application metadata for V8 startup snapshot construction. The lifecycle stops afterconfigWillLoad(no servers, timers, or connections) and skipsegg-readybroadcast.
Classes
class Agent
class Agent extends EggApplicationCore {}Singleton instance in Agent Worker, extend EggApplicationCore EggApplicationCore
constructor
constructor(options?: Omit<EggApplicationCoreOptions, 'type'>);Parameter options
method close
close: () => Promise<void>;method customEggLoader
protected override customEggLoader: () => typeof AgentWorkerLoader;method startKeepAlive
protected startKeepAlive: () => void;Start the keepalive timer that prevents the agent process from exiting when it has no pending I/O. Called from configDidLoad so that the timer is not created during snapshot build (configDidLoad is skipped in snapshot mode).
class AgentWorkerLoader
class AgentWorkerLoader extends EggApplicationLoader {}Agent worker process loader
See Also
https://github.com/eggjs/egg-core/blob/master/src/loader/egg_loader.ts
method load
load: () => Promise<void>;method loadConfig
loadConfig: () => Promise<void>;loadPlugin first, then loadConfig
class Application
class Application extends EggApplicationCore {}Singleton instance in App Worker, extend EggApplicationCore EggApplicationCore
constructor
constructor(options?: Omit<EggApplicationCoreOptions, 'type'>);Parameter options
property controller
controller: IController;property Helper
Helper: typeof Helper;reference to Helper {Helper} Application#Helper
property keys
readonly keys: string[];secret key for Application {String} Application#keys
property locals
locals: Record<string, any>;global locals for view {Object} Application#locals
See Also
Context#locals
property server
server?: http.Server;method customEggLoader
protected override customEggLoader: () => typeof AppWorkerLoader;method dumpConfig
dumpConfig: () => void;save routers to
run/router.json
method load
protected load: () => Promise<void>;method onClientError
onClientError: (err: any, socket: Socket) => void;method onServer
onServer: (server: http.Server) => void;method runInBackground
runInBackground: (scope: (ctx: Context) => Promise<void>, req?: unknown) => void;Run async function in the background
Parameter scope
the first args is an anonymous ctx
See Also
Context#runInBackground
method toAsyncFunction
toAsyncFunction: (fn: (...args: any[]) => any) => (...args: any[]) => any;Deprecated
keep compatible with egg 3.x
class AppWorkerLoader
class AppWorkerLoader extends EggApplicationLoader {}App worker process Loader, will load plugins
See Also
https://github.com/eggjs/egg-core/blob/master/src/loader/egg_loader.ts
method load
load: () => Promise<void>;Load all directories in convention 1.0.0
method loadConfig
loadConfig: () => Promise<void>;loadPlugin first, then loadConfig 1.0.0
class BaseContextClass
class BaseContextClass extends BaseContextClass$1 {}class Boot
class BaseHookClass implements ILifecycleBoot {}class Context
class Context extends Context$1 {}property acceptJSON
readonly acceptJSON: boolean;{Boolean} Context#acceptJSON
See Also
Request#acceptJSON 1.0.0
property app
app: Application;property cookies
readonly cookies: Cookies$1;Get the current visitor's cookies.
property coreLogger
readonly coreLogger: EggLogger;Logger for frameworks and plugins
{Logger} Context#coreLogger 1.0.0
property helper
readonly helper: Helper;Get helper instance from Application#Helper
{Helper} Context#helper 1.0.0
property httpclient
readonly httpclient: HttpClient;Get a wrapper httpclient instance contain ctx in the hold request process
{HttpClient} the wrapper httpclient instance
property httpClient
readonly httpClient: HttpClient;Alias to Context#httpclient
property ip
ip: string;{string} Context#ip
See Also
Request#ip 1.0.0
property locals
locals: Record<string, any>;locals is an object for view, you can use
app.localsandctx.localsto set variables, which will be used as data when view is rendering. The difference betweenapp.localsandctx.localsis the context level,app.localsis global level, andctx.localsis request level. when you getctx.locals, it will mergeapp.locals.when you set locals, only object is available
this.locals = {a: 1};this.locals = {b: 1};this.locals.c = 1;console.log(this.locals);{a: 1,b: 1,c: 1,};ctx.localshas cache, it only mergesapp.localsonce in one request.{Object} Context#locals
property logger
readonly logger: EggLogger;Logger for Application
{Logger} Context#logger 1.0.0
Example 1
this.logger.info('some request data: %j', this.request.body);this.logger.warn('WARNING!!!!');
property performanceStarttime
performanceStarttime: number;Request start timer using
performance.now(){Number} Context#performanceStarttime
property proxy
proxy: any;property queries
readonly queries: Record<string, string[]>;{Array} Context#queries
See Also
Request#queries 1.0.0
property query
readonly query: Record<string, string>;property realStatus
realStatus: number;{Number} Context#realStatus
See Also
Response#realStatus 1.0.0
property request
request: Request$1;property response
response: Response$1;property router
router: Router;Alias to Application#router
{Router} Context#router 1.0.0
Example 1
this.router.pathFor('post', { id: 12 });
property service
service: IService;property starttime
starttime: number;Request start time {Number} Context#starttime
property state
state: Record<string, any>;alias to Context#locals, compatible with koa that use this variable {Object} state
See Also
Context#locals
method curl
curl: ( url: HttpClientRequestURL, options?: HttpClientRequestOptions) => ReturnType<HttpClient['request']>;Shortcut for httpclient.curl
Context#curl
Parameter url
request url address.
Parameter options
options for request. {Object} see ContextHttpClient#curl
method getLogger
getLogger: (name: string) => EggLogger;Wrap app.loggers with context information, if a custom logger is defined by naming aLogger, then you can
ctx.getLogger('aLogger')Parameter name
logger name
method runInBackground
runInBackground: ( scope: (ctx: Context) => Promise<void>, taskName?: string) => void;Run async function in the background
Parameter scope
the first args is ctx
this.body = 'hi';this.runInBackground(async ctx => {await ctx.mysql.query(sql);await ctx.curl(url);});
class ContextHttpClient
class ContextHttpClient {}constructor
constructor(ctx: Context);property app
app: Application;property ctx
ctx: Context;method curl
curl: <T = any>( url: HttpClientRequestURL, options?: HttpClientRequestOptions) => Promise<HttpClientResponse<T>>;http request helper base on HttpClient, it will auto save httpclient log. Keep the same api with Application#curl.
Parameter url
request url address.
Parameter options
options for request.
method request
request: <T = any>( url: HttpClientRequestURL, options?: HttpClientRequestOptions) => Promise<HttpClientResponse<T>>;class Controller
class BaseContextClass extends BaseContextClass$1 {}class CookieLimitExceedError
class CookieLimitExceedError extends Error {}constructor
constructor(key: string, cookie: string);property cookie
cookie: string;property key
key: string;class EggApplicationCore
class EggApplicationCore extends EggCore {}Based on koa's Application
See Also
https://github.com/eggjs/egg-core
https://github.com/eggjs/koa/blob/master/src/application.ts EggCore
constructor
constructor(options?: EggApplicationCoreOptions);Parameter options
[type] - type of instance, Agent and Application both extend koa, type can determine what it is. - {String} [baseDir] - app root dir, default is
process.cwd()- {Object} [plugins] - custom plugin config, use it in unittest - {String} [mode] - process mode, can be cluster / single, default iscluster
property agent
agent?: Agent;property application
application?: Application;property BaseContextClass
BaseContextClass: typeof BaseContextClass$1;Retrieve base context class {BaseContextClass} BaseContextClass 1.0.0
property BaseHookClass
BaseHookClass: typeof BaseHookClass;Retrieve base context class {BaseHookClass} BaseHookClass
property Boot
Boot: typeof BaseHookClass;Retrieve base boot {Boot} BaseHookClass
property cluster
readonly cluster: (clientClass: unknown, options?: object) => any;Usage: new ApiClient({ cluster: app.cluster })
property config
readonly config: EggAppConfig$1;property ContextCookies
ContextCookies: any;property ContextHttpClient
ContextHttpClient: typeof ContextHttpClient;property ContextLogger
ContextLogger: any;property Controller
Controller: typeof BaseContextClass$1;Retrieve base controller {Controller} Controller 1.0.0
property coreLogger
readonly coreLogger: EggLogger;core logger for framework and plugins, log file is
$HOME/logs/{appname}/egg-web{Logger} 1.0.0
property ctxStorage
ctxStorage: AsyncLocalStorage<Context>;property currentContext
readonly currentContext: Context;Get the current request context from AsyncLocalStorage. This provides access to the context object for the current request lifecycle.
Returns
{Context | undefined} The current request context, or undefined if not in a request scope.
property env
env: string;app.env delegate app.config.env
Deprecated
property httpclient
readonly httpclient: HttpClient;Deprecated
please use httpClient instead httpClient {HttpClient}
property httpClient
readonly httpClient: HttpClient;HttpClient instance
Returns a transparent proxy that defers actual HttpClient construction until a method/property is first accessed. This allows plugins to modify
config.httpclient.lookupor other options during lifecycle hooks (e.g.configWillLoad,didLoad) even afterapp.httpClientis first referenced.See Also
https://github.com/node-modules/urllib {HttpClient}
property HttpClient
HttpClient: typeof HttpClient;property HttpClientNext
HttpClientNext: typeof HttpClient;property loader
loader: EggApplicationLoader;property loadFinished
readonly loadFinished: Promise<void>;Promise that resolves when the
load()method has finished. This is useful for callers that need to ensure config and metadata are fully loaded before proceeding.
property logger
readonly logger: EggLogger;application logger, log file is
$HOME/logs/{appname}/{appname}-web{Logger} 1.0.0
property loggers
readonly loggers: EggLoggers;All loggers contain logger, coreLogger and customLogger {Object} 1.0.0
property messenger
readonly messenger: IMessenger;property options
options: Required<EggApplicationCoreOptions>;property proxy
proxy: boolean;app.proxy delegate app.config.proxy
Deprecated
property Service
Service: typeof BaseContextClass$1;Retrieve base service {Service} Service 1.0.0
property Subscription
Subscription: typeof BaseContextClass$1;Retrieve base subscription {Subscription} Subscription 2.12.0
method clusterWrapper
clusterWrapper: (clientClass: unknown, options?: object) => any;Wrap the Client with Leader/Follower Pattern
almost the same as Agent.cluster API, the only different is that this method create Follower.
Parameter clientClass
client class function
Parameter options
[autoGenerate] - whether generate delegate rule automatically, default is true - {Function} [formatKey] - a method to transform the subscription info into a string,default is JSON.stringify - {Object} [transcode|JSON.stringify/parse] - {Function} encode - custom serialize method - {Function} decode - custom deserialize method - {Boolean} [isBroadcast] - whether broadcast subscription result to all followers or just one, default is true - {Number} [responseTimeout] - response timeout, default is 3 seconds - {Number} [maxWaitTime|30000] - leader startup max time, default is 30 seconds {ClientWrapper} wrapper
See Also
https://github.com/node-modules/cluster-client
method createAnonymousContext
createAnonymousContext: (req?: any) => EggContext;Create an anonymous context, the context isn't request level, so the request is mocked. then you can use context level API like
ctx.service{String} EggApplication#createAnonymousContextParameter req
if you want to mock request like querystring, you can pass an object to this function. {Context} context
method createContext
createContext: (req: IncomingMessage, res: ServerResponse) => Context;Create egg context EggApplication#createContext
Parameter req
node native Request object
Parameter res
node native Response object {Context} context object
method createHttpClient
createHttpClient: (options?: HttpClientOptions) => HttpClient;Create a new HttpClient instance with custom options
Parameter options
HttpClient init options
method curl
curl: <T = any>( url: HttpClientRequestURL, options?: HttpClientRequestOptions) => Promise<HttpClientResponse<T>>;http request helper base on httpclient, it will auto save httpclient log. Keep the same api with
httpclient.request(url, args).See https://github.com/node-modules/urllib#api-doc for more details.
Parameter url
request url address.
Parameter options
method {String} - Request method, defaults to GET. Could be GET, POST, DELETE or PUT. Alias 'type'. - data {Object} - Data to be sent. Will be stringify automatically. - dataType {String} - String - Type of response data. Could be
textorjson. If it'stext, the callback data would be a String. If it'sjson, the data of callback would be a parsed JSON Object. Default callback data would be a Buffer. - headers {Object} - Request headers. - timeout {Number} - Request timeout in milliseconds. Defaults to exports.TIMEOUT. Include remote server connecting timeout and response timeout. When timeout happen, will return ConnectionTimeout or ResponseTimeout. - auth {String} -username:passwordused in HTTP Basic Authorization. - followRedirect {Boolean} - follow HTTP 3xx responses as redirects. defaults to false. - gzip {Boolean} - let you get the res object when request connected, default false. alias customResponse - nestedQuerystring {Boolean} - urllib default use querystring to stringify form data which don't support nested object, will use qs instead of querystring to support nested object by set this option to true. - more options see https://github.com/node-modules/urllib {Object} - status {Number} - HTTP response status - headers {Object} - HTTP response headers - res {Object} - HTTP response meta - data {Object} - HTTP response bodyExample 1
const result = await app.curl('http://example.com/foo.json', {method: 'GET',dataType: 'json',});console.log(result.status, result.headers, result.data);
method customEggPaths
protected override customEggPaths: () => string[];method dumpConfig
dumpConfig: () => void;save app.config to
run/${type}_config.json
method dumpConfigToObject
dumpConfigToObject: () => { config: any; meta: any };dump out the config and meta object
method dumpManifest
dumpManifest: () => void;Generate and save startup manifest for faster subsequent startups. Only generates when no valid manifest was loaded (avoids overwriting during manifest-accelerated starts).
method dumpTiming
dumpTiming: () => void;method getLogger
getLogger: (name: string) => EggLogger;Get logger by name, it's equal to app.loggers['name'], but you can extend it with your own logical.
Parameter name
logger name {Logger} logger
method inspect
inspect: () => any;print the information when console.log(app) {Object} inspected app. 1.0.0
Example 1
console.log(app);=>{name: 'mock-app',env: 'test',subdomainOffset: 2,config: '<egg config>',controller: '<egg controller>',service: '<egg service>',middlewares: '<egg middlewares>',urllib: '<egg urllib>',loggers: '<egg loggers>'}
method load
protected load: () => Promise<void>;method loadConfig
protected loadConfig: () => Promise<void>;method runInAnonymousContextScope
runInAnonymousContextScope: <T = void>( scope: (ctx: Context) => Promise<T>, req?: unknown) => Promise<T>;Run async function in the anonymous context scope
Parameter scope
the first args is an anonymous ctx, scope should be async function
Parameter req
if you want to mock request like querystring, you can pass an object to this function.
See Also
Context#runInAnonymousContextScope
method snapshotDidDeserialize
protected snapshotDidDeserialize: () => void;Restore non-serializable resources after V8 heap deserialization. Recreates messenger, re-registers the egg-ready listener, reopens the logger streams closed during serialize, and re-attaches the process-level unhandledRejection listener.
method snapshotWillSerialize
protected snapshotWillSerialize: () => void;Clean up non-serializable resources before V8 heap serialization. Closes messenger (IPC listeners), logger streams and flush timers (file descriptors), and removes the process-level unhandledRejection listener.
The
EggLoggersinstance is intentionally kept (not discarded): plugins such as@eggjs/schedulecapture individual logger references during the load phase, before serialization. Replacing them with a freshEggLoggerson restore would leave those captured references pointing at closed streams (... log stream had been closed). Instead,snapshotDidDeserializereopens these same logger objects in place.
method toJSON
toJSON: () => any;class EggContextHttpClient
class HttpClient extends HttpClient$1 {}constructor
constructor(app: EggApplicationCore, options?: ClientOptions);method curl
curl: <T = any>( url: RequestURL, options?: HttpClientRequestOptions) => Promise<HttpClientResponse$1<T>>;method request
request: <T = any>( url: RequestURL, options?: HttpClientRequestOptions) => Promise<HttpClientResponse$1<T>>;class EggHttpClient
class HttpClient extends HttpClient$1 {}constructor
constructor(app: EggApplicationCore, options?: ClientOptions);method curl
curl: <T = any>( url: RequestURL, options?: HttpClientRequestOptions) => Promise<HttpClientResponse$1<T>>;method request
request: <T = any>( url: RequestURL, options?: HttpClientRequestOptions) => Promise<HttpClientResponse$1<T>>;class Helper
class Helper extends BaseContextClass {}The Helper class which can be used as utility function. We support developers to extend Helper through ${baseDir}/app/extend/helper.js , then you can use all method on
ctx.helperthat is a instance of Helper.
method pathFor
pathFor: (name: string, params: Record<string, any>) => string;Generate URL path(without host) for route. Takes the route name and a map of named params. Helper#pathFor
Parameter name
Router Name
Parameter params
Other params
Example 1
app.get('home', '/index.htm', 'home.index');ctx.helper.pathFor('home', { by: 'recent', limit: 20 })=> /index.htm?by=recent&limit=20{String} url path(without host)
method urlFor
urlFor: (name: string, params: Record<string, any>) => string;Generate full URL(with host) for route. Takes the route name and a map of named params. Helper#urlFor
Parameter name
Router name
Parameter params
Other params
Example 1
app.get('home', '/index.htm', 'home.index');ctx.helper.urlFor('home', { by: 'recent', limit: 20 })=> http://127.0.0.1:7001/index.htm?by=recent&limit=20{String} full url(with host)
class HttpClient
class HttpClient extends HttpClient$1 {}constructor
constructor(app: EggApplicationCore, options?: ClientOptions);method curl
curl: <T = any>( url: RequestURL, options?: HttpClientRequestOptions) => Promise<HttpClientResponse$1<T>>;method request
request: <T = any>( url: RequestURL, options?: HttpClientRequestOptions) => Promise<HttpClientResponse$1<T>>;class IHelper
class Helper extends BaseContextClass {}The Helper class which can be used as utility function. We support developers to extend Helper through ${baseDir}/app/extend/helper.js , then you can use all method on
ctx.helperthat is a instance of Helper.
method pathFor
pathFor: (name: string, params: Record<string, any>) => string;Generate URL path(without host) for route. Takes the route name and a map of named params. Helper#pathFor
Parameter name
Router Name
Parameter params
Other params
Example 1
app.get('home', '/index.htm', 'home.index');ctx.helper.pathFor('home', { by: 'recent', limit: 20 })=> /index.htm?by=recent&limit=20{String} url path(without host)
method urlFor
urlFor: (name: string, params: Record<string, any>) => string;Generate full URL(with host) for route. Takes the route name and a map of named params. Helper#urlFor
Parameter name
Router name
Parameter params
Other params
Example 1
app.get('home', '/index.htm', 'home.index');ctx.helper.urlFor('home', { by: 'recent', limit: 20 })=> http://127.0.0.1:7001/index.htm?by=recent&limit=20{String} full url(with host)
class MessageUnhandledRejectionError
class MessageUnhandledRejectionError extends Error {}constructor
constructor(err: Error, event: string | symbol, ...args: any[]);property args
args: any[];property event
event: string | symbol;class Request
class Request extends Request$1 {}property acceptJSON
readonly acceptJSON: boolean;detect if response should be json 1. url path ends with
.json2. response type is set to json 3. detect by request accept header{Boolean} Request#acceptJSON 1.0.0
property app
app: Application;property body
body: any;Request body, parsed from koa-bodyparser or @eggjs/multipart
property ctx
ctx: Context$1;property host
readonly host: string;Parse the "Host" header field host and support X-Forwarded-Host when a proxy is enabled. {String} Request#host
Example 1
ip + port
this.request.host=> '127.0.0.1:7001'or domain
this.request.host=> 'demo.eggjs.org'
property ip
ip: string;Get the request remote IPv4 address {String} Request#ip {String} IPv4 address
Example 1
this.request.ip=> '127.0.0.1'=> '111.10.2.1'
property ips
readonly ips: string[];Get all pass through ip addresses from the request. Enable only on
app.config.proxy = true{Array} Request#ips
Example 1
this.request.ips=> ['100.23.1.2', '201.10.10.2']
property protocol
readonly protocol: string;{String} Request#protocol
Example 1
this.request.protocol=> 'https'
property queries
readonly queries: Record<string, string[]>;get params pass by querystring, all value are Array type. Request#query {Array} Request#queries
Example 1
GET http://127.0.0.1:7001?a=b&a=c&o[foo]=bar&b[]=1&b[]=2&e=valthis.queries=>{"a": ["b", "c"],"o[foo]": ["bar"],"b[]": ["1", "2"],"e": ["val"]}
property query
query: Record<string, string>;get params pass by querystring, all values are of string type. {Object} Request#query
Example 1
GET http://127.0.0.1:7001?name=Foo&age=20&age=21this.query=> { 'name': 'Foo', 'age': '20' }GET http://127.0.0.1:7001?a=b&a=c&o[foo]=bar&b[]=1&b[]=2&e=valthis.query=>{"a": "b","o[foo]": "bar","b[]": "1","e": "val"}
property response
response: Response$1;class Response
class Response extends Response$1 {}property realStatus
realStatus: number;Get or set a real status code.
e.g.: Using 302 status redirect to the global error page instead of show current 500 status page. And access log should save 500 not 302, then the
realStatuscan help us find out the real status code. {Number} Response#realStatus {Number} The status code to be set.
class Service
class BaseContextClass extends BaseContextClass$1 {}class Subscription
class BaseContextClass extends BaseContextClass$1 {}Interfaces
interface ClientErrorResponse
interface ClientErrorResponse {}interface Config
interface EggAppConfig extends EggAppConfig$1 {}property baseDir
baseDir: string;property bodyParser
bodyParser: { enable: boolean; encoding: string; formLimit: string; jsonLimit: string; textLimit: string; strict: boolean; queryString: { arrayLimit: number; depth: number; parameterLimit: number; }; ignore?: IgnoreOrMatch; match?: IgnoreOrMatch; enableTypes?: string[]; extendTypes?: { json: string[]; form: string[]; text: string[]; }; /** Default is `'error'`, it will return `400` response when `Prototype-Poisoning` happen. */ onProtoPoisoning: 'error' | 'remove' | 'ignore'; onerror(err: any, ctx: Context$1): void;};The option of
bodyParsermiddlewareConfig#bodyParser {Boolean} enable - enable bodyParser or not, default to true {String | RegExp | Function | Array} ignore - won't parse request body when url path hit ignore pattern, can not set
ignorewhenmatchpresented {String | RegExp | Function | Array} match - will parse request body only when url path hit match pattern {String} encoding - body encoding config, default utf8 {String} formLimit - form body size limit, default 1mb {String} jsonLimit - json body size limit, default 1mb {String} textLimit - json body size limit, default 1mb {Boolean} strict - json body strict mode, if set strict value true, then only receive object and array json body {Number} queryString.arrayLimit - from item array length limit, default 100 {Number} queryString.depth - json value deep length, default 5 {Number} queryString.parameterLimit - parameter number limit, default 1000 {String[]} enableTypes - parser will only parse when request type hits enableTypes, default is ['json', 'form'] {Object} extendTypes - support extend types {String} onProtoPoisoning - Defines what action must take when parsing a JSON object with__proto__. Possible values are'error','remove'and'ignore'. Default is'error', it will return400response whenPrototype-Poisoninghappen.
property cluster
cluster: { listen: { path: string; port: number; hostname: string; /** * enable SO_REUSEPORT socket option for server listen, default is `false`. * Only available on Linux 3.9+, DragonFlyBSD 3.6+, FreeBSD 12.0+, Solaris 11.4, and AIX 7.2.5+. * @see https://nodejs.org/api/net.html#serverlistenoptions-callback */ reusePort?: boolean; };};property clusterClient
clusterClient: { maxWaitTime: number; responseTimeout: number;};property cookies
cookies: { sameSite?: string; httpOnly?: boolean;};property coreMiddleware
coreMiddleware: string[];property customLogger
customLogger: { [key: string]: EggLoggerOptions;};custom logger of egg
property dump
dump: { ignore: Set<string | RegExp>; timing: { slowBootActionMinDuration: number; };};It will ignore special keys when dumpConfig
property env
env: EggEnvType;The environment of egg
property HOME
HOME: string;The current HOME directory
property hostHeaders
hostHeaders: string;property httpclient
httpclient: HttpClientConfig;Configuration of httpclient in egg.
property ipHeaders
ipHeaders: string;Detect request' ip from specified headers, not case-sensitive. Only worked when config.proxy set to true.
property keys
keys: string;The key that signing cookies. It can contain multiple keys separated by
.Cookie secret key to sign and encrypt, see https://eggjs.org/core/cookie-and-session#cookie-secret-key
property logger
logger: EggLoggerConfig;logger options Config#logger {String} dir - directory of log files {String} encoding - log file encoding, defaults to utf8 {String} level - default log level, could be: DEBUG, INFO, WARN, ERROR or NONE, defaults to INFO in production {String} consoleLevel - log level of stdout, defaults to
INFOin local serverEnv, defaults toWARNin unittest, others isNONE{Boolean} disableConsoleAfterReady - disable logger console after app ready. defaults tofalseon local and unittest env, others istrue. {Boolean} outputJSON - log as JSON or not, defaults tofalse{Boolean} buffer - if enabled, flush logs to disk at a certain frequency to improve performance, defaults to true {String} errorLogName - file name of errorLogger {String} coreLogName - file name of coreLogger {String} agentLogName - file name of agent worker log {Object} coreLogger - custom config of coreLogger {Boolean} allowDebugAtProd - allow debug log at prod, defaults to false {Boolean} enableFastContextLogger - using the app logger instead of EggContextLogger, defaults to false
property maxIpsCount
maxIpsCount: number;property maxProxyCount
maxProxyCount: number;property meta
meta: MetaMiddlewareOptions;meta middleware options
property middleware
middleware: string[];property name
name: string;The name of the application
property notfound
notfound: NotFoundMiddlewareOptions;notfound middleware options
property overrideMethod
overrideMethod: { enable: boolean; allowedMethods: string[];};overrideMethod middleware options
property pkg
pkg: Record<string, any>;package.json
property protocolHeaders
protocolHeaders: string;property proxy
proxy: boolean;property rundir
rundir: string;property serverTimeout
serverTimeout: number | null;server timeout in milliseconds, default to 0 (no timeout).
for special request, just use
ctx.req.setTimeout(ms)See Also
https://nodejs.org/api/http.html#http_server_timeout
property siteFile
siteFile: SiteFileMiddlewareOptions;siteFile middleware options
property workerStartTimeout
workerStartTimeout: number;method onClientError
onClientError: ( err: Error, socket: Socket, app: Application) => ClientErrorResponse | Promise<ClientErrorResponse>;onClientError handler
index signature
[prop: string]: any;interface CreateTransparentProxyOptions
interface CreateTransparentProxyOptions<T> {}property bindFunctions
bindFunctions?: boolean;Whether to bind functions from the real object to the real instance. Defaults to true.
property createReal
createReal: () => T;Factory function to lazily create the real object. Called at most once, on first property access.
interface CustomLoaderConfig
interface CustomLoaderConfig extends Omit<FileLoaderOptions, 'inject' | 'target'> {}Custom Loader Configuration
interface EggAppConfig
interface EggAppConfig extends EggAppConfig$1 {}property baseDir
baseDir: string;property bodyParser
bodyParser: { enable: boolean; encoding: string; formLimit: string; jsonLimit: string; textLimit: string; strict: boolean; queryString: { arrayLimit: number; depth: number; parameterLimit: number; }; ignore?: IgnoreOrMatch; match?: IgnoreOrMatch; enableTypes?: string[]; extendTypes?: { json: string[]; form: string[]; text: string[]; }; /** Default is `'error'`, it will return `400` response when `Prototype-Poisoning` happen. */ onProtoPoisoning: 'error' | 'remove' | 'ignore'; onerror(err: any, ctx: Context$1): void;};The option of
bodyParsermiddlewareConfig#bodyParser {Boolean} enable - enable bodyParser or not, default to true {String | RegExp | Function | Array} ignore - won't parse request body when url path hit ignore pattern, can not set
ignorewhenmatchpresented {String | RegExp | Function | Array} match - will parse request body only when url path hit match pattern {String} encoding - body encoding config, default utf8 {String} formLimit - form body size limit, default 1mb {String} jsonLimit - json body size limit, default 1mb {String} textLimit - json body size limit, default 1mb {Boolean} strict - json body strict mode, if set strict value true, then only receive object and array json body {Number} queryString.arrayLimit - from item array length limit, default 100 {Number} queryString.depth - json value deep length, default 5 {Number} queryString.parameterLimit - parameter number limit, default 1000 {String[]} enableTypes - parser will only parse when request type hits enableTypes, default is ['json', 'form'] {Object} extendTypes - support extend types {String} onProtoPoisoning - Defines what action must take when parsing a JSON object with__proto__. Possible values are'error','remove'and'ignore'. Default is'error', it will return400response whenPrototype-Poisoninghappen.
property cluster
cluster: { listen: { path: string; port: number; hostname: string; /** * enable SO_REUSEPORT socket option for server listen, default is `false`. * Only available on Linux 3.9+, DragonFlyBSD 3.6+, FreeBSD 12.0+, Solaris 11.4, and AIX 7.2.5+. * @see https://nodejs.org/api/net.html#serverlistenoptions-callback */ reusePort?: boolean; };};property clusterClient
clusterClient: { maxWaitTime: number; responseTimeout: number;};property cookies
cookies: { sameSite?: string; httpOnly?: boolean;};property coreMiddleware
coreMiddleware: string[];property customLogger
customLogger: { [key: string]: EggLoggerOptions;};custom logger of egg
property dump
dump: { ignore: Set<string | RegExp>; timing: { slowBootActionMinDuration: number; };};It will ignore special keys when dumpConfig
property env
env: EggEnvType;The environment of egg
property HOME
HOME: string;The current HOME directory
property hostHeaders
hostHeaders: string;property httpclient
httpclient: HttpClientConfig;Configuration of httpclient in egg.
property ipHeaders
ipHeaders: string;Detect request' ip from specified headers, not case-sensitive. Only worked when config.proxy set to true.
property keys
keys: string;The key that signing cookies. It can contain multiple keys separated by
.Cookie secret key to sign and encrypt, see https://eggjs.org/core/cookie-and-session#cookie-secret-key
property logger
logger: EggLoggerConfig;logger options Config#logger {String} dir - directory of log files {String} encoding - log file encoding, defaults to utf8 {String} level - default log level, could be: DEBUG, INFO, WARN, ERROR or NONE, defaults to INFO in production {String} consoleLevel - log level of stdout, defaults to
INFOin local serverEnv, defaults toWARNin unittest, others isNONE{Boolean} disableConsoleAfterReady - disable logger console after app ready. defaults tofalseon local and unittest env, others istrue. {Boolean} outputJSON - log as JSON or not, defaults tofalse{Boolean} buffer - if enabled, flush logs to disk at a certain frequency to improve performance, defaults to true {String} errorLogName - file name of errorLogger {String} coreLogName - file name of coreLogger {String} agentLogName - file name of agent worker log {Object} coreLogger - custom config of coreLogger {Boolean} allowDebugAtProd - allow debug log at prod, defaults to false {Boolean} enableFastContextLogger - using the app logger instead of EggContextLogger, defaults to false
property maxIpsCount
maxIpsCount: number;property maxProxyCount
maxProxyCount: number;property meta
meta: MetaMiddlewareOptions;meta middleware options
property middleware
middleware: string[];property name
name: string;The name of the application
property notfound
notfound: NotFoundMiddlewareOptions;notfound middleware options
property overrideMethod
overrideMethod: { enable: boolean; allowedMethods: string[];};overrideMethod middleware options
property pkg
pkg: Record<string, any>;package.json
property protocolHeaders
protocolHeaders: string;property proxy
proxy: boolean;property rundir
rundir: string;property serverTimeout
serverTimeout: number | null;server timeout in milliseconds, default to 0 (no timeout).
for special request, just use
ctx.req.setTimeout(ms)See Also
https://nodejs.org/api/http.html#http_server_timeout
property siteFile
siteFile: SiteFileMiddlewareOptions;siteFile middleware options
property workerStartTimeout
workerStartTimeout: number;method onClientError
onClientError: ( err: Error, socket: Socket, app: Application) => ClientErrorResponse | Promise<ClientErrorResponse>;onClientError handler
index signature
[prop: string]: any;interface EggApplicationCoreOptions
interface EggApplicationCoreOptions extends Omit<EggCoreOptions, 'baseDir'> {}property baseDir
baseDir?: string;property clusterPort
clusterPort?: number;property mode
mode?: 'cluster' | 'single';interface EggLoggerConfig
interface EggLoggerConfig extends Omit<EggLoggersOptions, 'type'> {}logger config of egg
property allowDebugAtProd
allowDebugAtProd?: boolean;allow debug log at prod, defaults to
false
property coreLogger
coreLogger?: Partial<EggLoggerOptions>;custom config of coreLogger
property disableConsoleAfterReady
disableConsoleAfterReady?: boolean;disable logger console after app ready. defaults to
falseon local and unittest env, others istrue.
property enableFastContextLogger
enableFastContextLogger?: boolean;using the app logger instead of EggContextLogger, defaults to
false
property enablePerformanceTimer
enablePerformanceTimer?: boolean;[deprecated] Defaults to
true.
interface EggPlugin
interface EggPlugin {}build-in plugin list
property development
development?: EggPluginItem;property i18n
i18n?: EggPluginItem;property jsonp
jsonp?: EggPluginItem;property logrotator
logrotator?: EggPluginItem;property multipart
multipart?: EggPluginItem;property onerror
onerror?: EggPluginItem;property schedule
schedule?: EggPluginItem;property security
security?: EggPluginItem;property session
session?: EggPluginItem;property static
static?: EggPluginItem;property view
view?: EggPluginItem;property watcher
watcher?: EggPluginItem;index signature
[key: string]: EggPluginItem | undefined;interface EggPluginMeta
interface EggPluginMeta {}Define plugin meta with type safety
property dependencies
dependencies?: string[];the dependent plugins, you can use the plugin name
property enable
enable: boolean;whether enabled
property env
env?: EggEnvType[];specify the serverEnv that only enable the plugin in it, default to all envs
property name
name: string;the plugin name, it can be used in
dep
property optionalDependencies
optionalDependencies?: string[];the optional dependent plugins.
property path
path: string;the directory of the plugin package
interface HttpClientConfig
interface HttpClientConfig {}property allowH2
allowH2?: boolean;Allow http2
property interceptors
interceptors?: Dispatcher.DispatcherComposeInterceptor[];Interceptors for request composition, applied via
Dispatcher.compose(). Each interceptor receives adispatchfunction and returns a newdispatchfunction.Example 1
// config.default.tsconfig.httpclient = {interceptors: [(dispatch) => (opts, handler) => {opts.headers = { ...opts.headers, 'x-trace-id': generateTraceId() };return dispatch(opts, handler);},],};
property lookup
lookup?: LookupFunction;property request
request?: RequestOptions;Default request args for httpclient
property timeout
timeout?: number;Request timeout
property useHttpClientNext
useHttpClientNext?: boolean;Deprecated
keep compatible with egg 3.x, no more used
interface HttpClientRequestOptions
interface HttpClientRequestOptions extends RequestOptions {}interface IController
interface IController extends Record<string, any> {}The empty interface
IControlleris a placeholder, for egg to auto injection controller to app.controllerExample 1
import { Controller } from 'egg'; class HomeController extends Controller { async index() {} }
declare module 'egg' { export interface IController { home: HomeController; } }
Now I can get app.controller.home in the application.
interface IEggPluginItem
interface IEggPluginItem {}plugin config item interface
interface IService
interface IService extends Record<string, any> {}The empty interface
IServiceis a placeholder, for egg to auto injection service to ctx.serviceExample 1
import { Service } from 'egg'; class FooService extends Service { async bar() {} }
declare module 'egg' { export interface IService { foo: FooService; } }
Now I can get ctx.service.foo at controller and other service file.
interface SingleModeAgent
interface SingleModeAgent extends Agent {}property app
app: SingleModeApplication;interface SingleModeApplication
interface SingleModeApplication extends Application {}property agent
agent: SingleModeAgent;interface StartEggOptions
interface StartEggOptions {}property baseDir
baseDir?: string;directory of application, default to
process.cwd()
property env
env?: string;property framework
framework?: string;specify framework that can be absolute path or npm package
property ignoreWarning
ignoreWarning?: boolean;ignore single process mode warning
property loaderFS
loaderFS?: LoaderFS;Loader-facing filesystem abstraction
property metadataOnly
metadataOnly?: boolean;Skip lifecycle hooks, only trigger loadMetadata for manifest generation
property mode
mode?: 'single';property plugins
plugins?: EggPlugin;property snapshot
snapshot?: boolean;When true, load application metadata for V8 startup snapshot construction. The lifecycle stops after configWillLoad (no servers, timers, or connections) and skips
egg-readybroadcast.ready()resolves when loading completes.
Type Aliases
type EggConfigFactory
type EggConfigFactory = (appInfo: EggAppInfo) => PartialEggConfig;Configuration factory function return type
type EggContext
type EggContext = Context;type EggEnvType
type EggEnvType = 'local' | 'unittest' | 'prod' | string;egg env type
type EggPluginFactory
type EggPluginFactory = ( options?: EggPluginOptions) => Record<string, EggPluginMeta>;Egg plugin factory type, the return value is a record of plugin name and plugin meta.
type EggPluginItem
type EggPluginItem = IEggPluginItem | boolean;type EggPluginOptions
type EggPluginOptions = PartialDeep<Omit<EggPluginMeta, 'name'>>;Egg plugin options, user can't provide name, it will be generated by the plugin factory.
type MiddlewareFunc
type MiddlewareFunc<T extends Context = Context> = MiddlewareFunc$1<T>;type PartialEggConfig
type PartialEggConfig = PartialDeep<EggAppConfig>;Partial EggAppConfig
type PowerPartial
type PowerPartial<T> = PartialDeep<T>;Powerful Partial, Support adding ? modifier to a mapped property in deep level
Example 1
import { PowerPartial, EggAppConfig } from 'egg';
// { view: { defaultEngines: string } } => { view?: { defaultEngines?: string } } type EggConfig = PowerPartial
Deprecated
use
PartialDeepinstead
type RequestObjectBody
type RequestObjectBody = Record<string, any>;Package Files (21)
- dist/app/extend/context.d.ts
- dist/app/extend/helper.d.ts
- dist/app/extend/request.d.ts
- dist/app/extend/response.d.ts
- dist/index.d.ts
- dist/lib/agent.d.ts
- dist/lib/application.d.ts
- dist/lib/core/base_context_class.d.ts
- dist/lib/core/base_hook_class.d.ts
- dist/lib/core/context_httpclient.d.ts
- dist/lib/core/httpclient.d.ts
- dist/lib/core/utils.d.ts
- dist/lib/define.d.ts
- dist/lib/egg.d.ts
- dist/lib/error/CookieLimitExceedError.d.ts
- dist/lib/error/MessageUnhandledRejectionError.d.ts
- dist/lib/loader/AgentWorkerLoader.d.ts
- dist/lib/loader/AppWorkerLoader.d.ts
- dist/lib/snapshot.d.ts
- dist/lib/start.d.ts
- dist/lib/types.d.ts
Dependencies (42)
- @eggjs/ajv-plugin
- @eggjs/aop-plugin
- @eggjs/cluster
- @eggjs/controller-plugin
- @eggjs/cookies
- @eggjs/core
- @eggjs/dal-plugin
- @eggjs/development
- @eggjs/errors
- @eggjs/eventbus-plugin
- @eggjs/extend2
- @eggjs/i18n
- @eggjs/jsonp
- @eggjs/logrotator
- @eggjs/multipart
- @eggjs/onerror
- @eggjs/orm-plugin
- @eggjs/schedule
- @eggjs/schedule-plugin
- @eggjs/security
- @eggjs/session
- @eggjs/static
- @eggjs/tegg
- @eggjs/tegg-config
- @eggjs/tegg-plugin
- @eggjs/utils
- @eggjs/view
- @eggjs/watcher
- circular-json-for-egg
- cluster-client
- egg-logger
- graceful
- humanize-ms
- is-type-of
- koa-bodyparser
- koa-override
- onelogger
- performance-ms
- sendmessage
- type-fest
- urllib
- utility
Dev Dependencies (17)
Peer Dependencies (0)
No peer dependencies.
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/egg.
- Markdown[](https://www.jsdocs.io/package/egg)
- HTML<a href="https://www.jsdocs.io/package/egg"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 4429 ms. - Missing or incorrect documentation? Open an issue for this package.
