### Install and Run in Development Source: https://github.com/eggjs/egg/blob/next/tools/create-egg/src/templates/simple-ts/README.md Install dependencies and start the development server. Open the application in your browser. ```bash npm i npm run dev open http://localhost:7001/ ``` -------------------------------- ### Egg.js Quickstart Installation Source: https://github.com/eggjs/egg/blob/next/packages/egg/README.md Use this command to initialize a new Egg.js project with a simple type. Ensure Node.js version 20.19.0 or higher is installed. ```bash mkdir showcase && cd showcase npm init egg --type=simple # Optionally pnpm create egg --type=simple pnpm install pnpm run dev open http://localhost:7001 ``` -------------------------------- ### Install Dependencies and Start Development Server Source: https://github.com/eggjs/egg/blob/next/tools/create-egg/src/templates/egg3-simple-ts/README.md Run these commands to install project dependencies and start the development server. Avoid running `tsc` in development mode; use `npm run clean` if needed before restarting the dev server. ```bash $ npm i $ npm run dev $ open http://localhost:7001/ ``` -------------------------------- ### Plugin Initialization: Async Startup Source: https://github.com/eggjs/egg/blob/next/site/docs/advanced/plugin.md Handle asynchronous initialization tasks before the application starts using `app.beforeStart`. This example initializes a custom client and waits for it to be ready. ```javascript // ${plugin_root}/app.js const MyClient = require('my-client'); module.exports = (app) => { app.myClient = new MyClient(); app.myClient.on('error', (err) => { app.coreLogger.error(err); }); app.beforeStart(async () => { await app.myClient.ready(); app.coreLogger.info('my client is ready'); }); }; ``` -------------------------------- ### Agent Initialization: Async Startup Source: https://github.com/eggjs/egg/blob/next/site/docs/advanced/plugin.md Handle asynchronous initialization tasks for the agent process before it starts using `agent.beforeStart`. This example initializes a custom client and waits for it to be ready. ```javascript // ${plugin_root}/agent.js const MyClient = require('my-client'); module.exports = (agent) => { agent.myClient = new MyClient(); agent.myClient.on('error', (err) => { agent.coreLogger.error(err); }); agent.beforeStart(async () => { await agent.myClient.ready(); agent.coreLogger.info('my client is ready'); }); }; ``` -------------------------------- ### Example Routing Rules in app/router.js Source: https://github.com/eggjs/egg/blob/next/site/docs/basics/router.md Provides practical examples of defining various routes, including simple GET, POST with middleware, and versioned API routes. ```javascript // app/router.js module.exports = (app) => { const { router, controller } = app; router.get('/home', controller.home); router.get('/user/:id', controller.user.page); router.post('/admin', isAdmin, controller.admin); router.post('/user', isLoginUser, hasAdminPermission, controller.user.create); router.post('/api/v1/comments', controller.v1.comments.create); // app/controller/v1/comments.js }; ``` -------------------------------- ### Plugin Initialization: Read Local Config Source: https://github.com/eggjs/egg/blob/next/site/docs/advanced/plugin.md Perform synchronous initialization tasks when the application starts by reading local configuration files. This example reads a 'data.bin' file. ```javascript // ${plugin_root}/app.js const fs = require('fs'); const path = require('path'); module.exports = (app) => { app.customData = fs.readFileSync(path.join(app.config.baseDir, 'data.bin')); app.coreLogger.info('read data ok'); }; ``` -------------------------------- ### Install MySQL on macOS Source: https://github.com/eggjs/egg/blob/next/site/docs/tutorials/sequelize.md Use Homebrew to install and start the MySQL service on macOS. ```bash brew install mysql brew services start mysql ``` -------------------------------- ### Build and Start Production Server Source: https://github.com/eggjs/egg/blob/next/tools/create-egg/src/templates/tegg/README.md Build the project for production and start the production server. ```bash npm run build npm start ``` -------------------------------- ### Start Local Development Services (MySQL, Redis) Source: https://github.com/eggjs/egg/blob/next/README.md Use this command to start local MySQL and Redis services required for certain DAL, ORM, and ecosystem benchmark tests. Ensure Docker is installed and running. ```bash utoo run dev:services:start ``` -------------------------------- ### Use Bootstrap for Setup Source: https://github.com/eggjs/egg/blob/next/site/docs/core/mock.md Utilize the bootstrap helper for convenient common setup and teardown in tests. ```javascript const { app, mock, assert } = require('egg-mock/bootstrap'); describe('test/controller/home.test.js', () => { // test cases }); ``` -------------------------------- ### End-to-End Example Source: https://github.com/eggjs/egg/blob/next/packages/skills/egg-unittest/references/http-test.md Provides a comprehensive example of testing controllers with multiple scenarios for GET and POST requests. ```APIDOC ## End-to-End Controller Testing ### Description This example demonstrates testing user-related controllers, including fetching a user by ID, handling user not found scenarios, creating a new user, and validating input parameters for creation. ### Scenarios #### GET /api/users/:id - **Should return user**: Verifies a successful retrieval of a user. - **Should return 404 when user not found**: Checks the 404 response for non-existent users. #### POST /api/users - **Should create user**: Tests the successful creation of a user with valid data. - **Should return 422 with invalid params**: Validates the 422 response for invalid input during user creation. ### Request Example ```typescript import assert from 'node:assert'; import { app } from '@eggjs/mock/bootstrap'; describe('test/controller/user.test.ts', () => { describe('GET /api/users/:id', () => { it('should return user', () => { return app.httpRequest().get('/api/users/1').expect(200).expect({ id: '1', name: 'test' }); }); it('should return 404 when user not found', () => { return app.httpRequest().get('/api/users/999').expect(404); }); }); describe('POST /api/users', () => { it('should create user', () => { app.mockCsrf(); return app.httpRequest().post('/api/users').send({ name: 'new user', email: 'new@example.com' }).expect(201); }); it('should return 422 with invalid params', () => { app.mockCsrf(); return app.httpRequest().post('/api/users').send({ name: '' }).expect(422); }); }); }); ``` ``` -------------------------------- ### Hello Koa Example Source: https://github.com/eggjs/egg/blob/next/packages/koa/Readme.md A basic Koa application that responds with 'Hello Koa' to all requests. Ensure you have Node.js v22.18.0 or higher installed. ```typescript import { Application } from '@eggjs/koa'; const app = new Application(); // response app.use((ctx) => { ctx.body = 'Hello Koa'; }); app.listen(3000); ``` -------------------------------- ### startEgg(options) / start(options) Source: https://context7.com/eggjs/egg/llms.txt Starts both an Agent and an Application in the same process, preferred for development, testing, and containerized environments. ```APIDOC ## `startEgg(options)` / `start(options)` — Start egg in single-process mode Starts both an Agent and an Application in the same process, which is the preferred mode for development, testing, and containerized environments where multi-process is unnecessary. ```typescript import { start } from 'egg'; const app = await start({ baseDir: process.cwd(), framework: 'egg', // optional: resolves from package.json egg.framework if omitted env: 'local', // plugins: { redis: { enable: true, path: '...' } } // inject extra plugins at runtime }); // app is a SingleModeApplication; agent is available as app.agent console.log('App ready, env:', app.config.env); // Graceful shutdown process.on('SIGTERM', async () => { await app.close(); }); ``` ``` -------------------------------- ### Client Implementation Example Source: https://github.com/eggjs/egg/blob/next/site/docs/advanced/cluster-client.md An example of a client class implementing subscribe, publish, and getData methods. Remember to invoke ready after initialization. ```javascript const { Base } = require('sdk-base'); class Client extends Base { constructor(options) { super(options); // remember to invoke ready after initialization is successful this.ready(true); } /** * Subscribe * * @param {Object} info - subscription information (a JSON object, try not to include attributes such as Function, Buffer, Date) * @param {Function} listener - monitoring callback function, receives a parameter as the result of monitoring */ subscribe(info, listener) { // ... } /** * Publish * * @param {Object} info - publishing information, which is similar to that of subscribe described above */ publish(info) { // ... } /** * Get data (invoke) * * @param {String} id - id * @return {Object} result */ async getData(id) { // ... } } ``` -------------------------------- ### Install passport-local Source: https://github.com/eggjs/egg/blob/next/site/docs/tutorials/passport.md Install the passport-local strategy for account password login. ```bash $ npm i --save passport-local ``` -------------------------------- ### Install a Plugin Source: https://github.com/eggjs/egg/blob/next/site/docs/basics/plugin.md Install a plugin using npm. It's recommended to use the caret versioning (`^`) for dependencies. ```bash $ npm i egg-mysql --save ``` -------------------------------- ### Install wrk benchmarking tool Source: https://github.com/eggjs/egg/blob/next/tegg/benchmark/http/README.md Install the wrk tool, a command-line HTTP benchmarking tool, using Homebrew. This is a prerequisite for running the benchmarks. ```bash brew install wrk ``` -------------------------------- ### Install egg-socket.io Source: https://github.com/eggjs/egg/blob/next/site/docs/tutorials/socketio.md Install the egg-socket.io plugin using npm. ```bash $ npm i egg-socket.io --save ``` -------------------------------- ### Start Application in Production Environment Source: https://github.com/eggjs/egg/blob/next/site/docs/basics/env.md Conveniently start your application in a specific environment, such as production, by setting the `EGG_SERVER_ENV` environment variable before running the start command. ```shell EGG_SERVER_ENV=prod npm start ``` -------------------------------- ### Basic Node.js Cluster Setup Source: https://github.com/eggjs/egg/blob/next/site/docs/core/cluster-and-ipc.md This example demonstrates how to use the Node.js cluster module to fork worker processes and handle incoming HTTP requests. The master process forks workers based on the number of CPU cores, and worker processes listen on port 8000. ```javascript const cluster = require('cluster'); const http = require('http'); const numCPUs = require('os').cpus().length; if (cluster.isMaster) { // Fork workers. for (let i = 0; i < numCPUs; i++) { cluster.fork(); } cluster.on('exit', function (worker, code, signal) { console.log('worker ' + worker.process.pid + ' died'); }); } else { // Workers can share any TCP connection // In this case it is an HTTP server http .createServer(function (req, res) { res.writeHead(200); res.end('hello world\n'); }) .listen(8000); } ``` -------------------------------- ### Install @eggjs/schedule-decorator Source: https://github.com/eggjs/egg/blob/next/tegg/core/schedule-decorator/README.md Install the package using npm. ```shell npm i --save @eggjs/schedule-decorator ``` -------------------------------- ### Installing ioredis-mock for Unit Tests Source: https://github.com/eggjs/egg/blob/next/plugins/redis/README.md Install `ioredis-mock` and its types as development dependencies to replace the real Redis client during unit tests. ```bash npm i --save-dev ioredis-mock @types/ioredis-mock ``` -------------------------------- ### Install All Dependencies Source: https://github.com/eggjs/egg/blob/next/tegg/CLAUDE.md Install all project dependencies, respecting catalog versions, from the monorepo root. ```bash pnpm install ``` -------------------------------- ### Start Cluster with Promise Callback Source: https://github.com/eggjs/egg/blob/next/packages/cluster/README.md Start the cluster and handle the promise to log a message when the application has started. The master process will exit if an error occurs. ```javascript startCluster(options).then(() => { console.log('started'); }); ``` -------------------------------- ### Start Application with Proxy Source: https://github.com/eggjs/egg/blob/next/site/docs/core/httpclient.md Start your application with the `http_proxy` environment variable set to enable the configured proxy settings for HTTP client requests. ```bash $ http_proxy=http://127.0.0.1:8888 npm run dev ``` -------------------------------- ### Start Egg in Single-Process Mode Source: https://context7.com/eggjs/egg/llms.txt Use `start` (or `startEgg`) for development, testing, or containerized environments where multi-process is not needed. This mode starts both an Agent and an Application in the same process. ```typescript import { start } from 'egg'; const app = await start({ baseDir: process.cwd(), framework: 'egg', // optional: resolves from package.json egg.framework if omitted env: 'local', // plugins: { redis: { enable: true, path: '...' } } // inject extra plugins at runtime }); // app is a SingleModeApplication; agent is available as app.agent console.log('App ready, env:', app.config.env); // Graceful shutdown process.on('SIGTERM', async () => { await app.close(); }); ``` -------------------------------- ### Install @eggjs/mock Source: https://github.com/eggjs/egg/blob/next/plugins/mock/README.md Install the mock library as a development dependency. ```bash npm i @eggjs/mock --save-dev ``` -------------------------------- ### Install Production Dependencies and Package Application Source: https://github.com/eggjs/egg/blob/next/site/docs/core/deployment.md Install only production dependencies and then package the application and its dependencies into a tgz file for deployment. ```bash $ cd baseDir $ npm install --production $ tar -zcvf ../release.tgz . ``` -------------------------------- ### Install Koa and Node.js Source: https://github.com/eggjs/egg/blob/next/packages/koa/docs/api/index.md Install a supported Node.js version and the Koa package. Then, run your Koa application. ```bash nvm install 7 npm i koa node my-koa-app.js ``` -------------------------------- ### Install koa-static-cache Source: https://github.com/eggjs/egg/blob/next/packages/koa-static-cache/README.md Install the koa-static-cache package using npm. ```bash npm install @eggjs/koa-static-cache ``` -------------------------------- ### Install Moment.js for Date Formatting Source: https://github.com/eggjs/egg/blob/next/site/docs/intro/quickstart.md Install the moment.js library to format dates. This is used in custom helpers for displaying relative times. ```bash npm i moment --save ``` -------------------------------- ### Install project dependencies Source: https://github.com/eggjs/egg/blob/next/tegg/benchmark/http/README.md Install all necessary Node.js dependencies for the project using npm. This command should be run in the project's root directory. ```bash npm install ``` -------------------------------- ### Install egg-passport and egg-passport-github Source: https://github.com/eggjs/egg/blob/next/site/docs/tutorials/passport.md Install the necessary packages for Passport integration and the GitHub strategy. ```bash $ npm i --save egg-passport $ npm i --save egg-passport-github ``` -------------------------------- ### Example Application Loading Order Source: https://github.com/eggjs/egg/blob/next/site/docs/advanced/loader.md Demonstrates the final loading order of plugins, frameworks, and the application based on dependencies and inheritance. ```text => plugin1 => plugin3 => plugin2 => egg => framework1 => app ``` -------------------------------- ### Install Redis Plugin Source: https://github.com/eggjs/egg/blob/next/plugins/session/README.md To use Redis as an external session store, first install the `@eggjs/redis` package. ```bash npm i --save @eggjs/redis ``` -------------------------------- ### Example GET Request to Server Source: https://github.com/eggjs/egg/blob/next/site/docs/core/security.md This `curl` command sends a simple GET request to the server. The response shows the server's headers and a `Set-Cookie` header, indicating that an httpOnly cookie has been set. ```bash curl -i http://127.0.0.1:7001 ``` -------------------------------- ### Initialize Egg.js Project Step-by-Step Source: https://github.com/eggjs/egg/blob/next/site/docs/intro/quickstart.md Commands to manually create a project directory, initialize npm, and install Egg.js and Egg.js bin dependencies. ```bash mkdir egg-example cd egg-example npm init npm i egg --save npm i egg-bin --save-dev ``` -------------------------------- ### Install @eggjs/tracer Source: https://github.com/eggjs/egg/blob/next/plugins/tracer/README.md Install the tracer plugin using npm. This is the first step to enable tracing in your Egg.js application. ```bash npm i @eggjs/tracer ``` -------------------------------- ### Start Development Server with egg-bin dev Source: https://github.com/eggjs/egg/blob/next/tools/egg-bin/README.md Use the 'dev' command to start the Egg.js application in development mode, running a master, agent, and worker. ```bash egg-bin dev ``` -------------------------------- ### Get Translated Text Source: https://github.com/eggjs/egg/blob/next/site/docs/core/i18n.md Use the `__` function (or its alias `gettext`) to retrieve translated strings. This example demonstrates fetching the 'Email' translation. ```javascript ctx.__('Email'); ``` -------------------------------- ### Build a Snapshot Source: https://github.com/eggjs/egg/blob/next/site/docs/advanced/snapshot.md Instructions on how to create a V8 startup snapshot using Egg's `buildSnapshot` helper and the Node.js command-line interface. ```APIDOC ## Build a Snapshot Create a snapshot entry file: ```ts import { buildSnapshot } from 'egg'; await buildSnapshot({ baseDir: import.meta.dirname, }); ``` Then build the blob with Node.js: ```bash node --snapshot-blob=snapshot.blob --build-snapshot snapshot-entry.mjs ``` During snapshot build, Egg runs with `snapshot: true`. In this mode Egg loads application metadata but stops after `configWillLoad`, so hooks such as `configDidLoad`, `didLoad`, `willReady`, `didReady`, and `serverDidReady` are deferred until restore time. ``` -------------------------------- ### Extend Egg.js Application Lifecycle Source: https://github.com/eggjs/egg/blob/next/site/docs/tutorials/typescript.md Hook into the application's lifecycle using TypeScript. This example demonstrates using `app.beforeStart` to perform an asynchronous operation before the application starts. ```typescript // app.ts export default (app) => { app.beforeStart(async () => { await Promise.resolve('egg + ts'); }); }; ``` -------------------------------- ### Initialize Test Setup and Data Cleanup Source: https://github.com/eggjs/egg/blob/next/site/docs/tutorials/sequelize.md Set up the test environment by introducing the factory and ensuring database tables are cleared after each test case using `truncate: true` and `force: true`. ```javascript const { app } = require('egg-mock/bootstrap'); const factories = require('./factories'); before(() => factories(app)); afterEach(async () => { // clear database after each test case await Promise.all([app.model.User.destroy({ truncate: true, force: true })]); }); ``` -------------------------------- ### Dockerfile for Manifest Generation Source: https://github.com/eggjs/egg/blob/next/site/docs/core/manifest.md Integrates startup manifest generation into a Dockerfile. The manifest is generated after dependencies are installed and the application is built, ensuring it's available for optimized container starts. ```dockerfile # Install dependencies and build RUN npm install --production RUN npm run build # Generate startup manifest RUN npx egg-bin manifest generate --env=prod # Start the app (manifest is used automatically) CMD ["npm", "start"] ``` -------------------------------- ### Initial Commit and Push Source: https://github.com/eggjs/egg/wiki/How-to-create-a-new-repository Add the LICENSE file, make the initial commit, and push it to the remote repository. ```bash $ git add LICENSE $ git commit -m 'feat: init project' $ git push ``` -------------------------------- ### Initialize Egg.js Project Source: https://github.com/eggjs/egg/blob/next/site/docs/tutorials/sequelize.md Create a new Egg.js project and install its dependencies. ```bash mkdir sequelize-project && cd sequelize-project npm init egg --type=simple npm i ``` -------------------------------- ### Replace `app.beforeStart` with Class Method Source: https://github.com/eggjs/egg/blob/next/site/docs/advanced/loader-update.md Use `willReady` for application-level `beforeStart` logic and `didLoad` for plugin-level logic within an `AppBootHook` class. ```javascript module.exports = (app) => { app.beforeStart(async () => { // Here's where your codes were before }); }; ``` ```javascript // app.js or agent.js: class AppBootHook { constructor(app) { this.app = app; } async didLoad() { // Please put your codes of `app.beforeStart` here for your plugin } async willReady() { // Please put your codes of `app.beforeStart` here for your application } } module.exports = AppBootHook; ``` -------------------------------- ### Install @eggjs/background-task Source: https://github.com/eggjs/egg/blob/next/tegg/core/background-task/README.md Install the package using npm. ```sh npm i --save @eggjs/background-task ``` -------------------------------- ### Install @eggjs/errors Source: https://github.com/eggjs/egg/blob/next/packages/errors/README.md Install the package using npm. ```bash npm i @eggjs/errors --save ``` -------------------------------- ### Install @eggjs/path-matching Source: https://github.com/eggjs/egg/blob/next/packages/path-matching/README.md Install the package using npm. ```bash npm install @eggjs/path-matching ``` -------------------------------- ### Create an App Instance Source: https://github.com/eggjs/egg/blob/next/site/docs/core/mock.md Create an application instance for testing purposes. Ensure the app is ready before proceeding and closed after tests. ```javascript const mock = require('@eggjs/mock'); describe('test/controller/home.test.js', () => { let app; before(async () => { app = mock.app({ baseDir: 'path/to/your/app' }); await app.ready(); }); after(() => app.close()); }); ``` -------------------------------- ### Initialize Sequelize Configuration and Migrations Source: https://github.com/eggjs/egg/blob/next/site/docs/tutorials/sequelize.md Use npx sequelize to initialize the configuration file and the migrations directory. ```bash npx sequelize init:config npx sequelize init:migrations ``` -------------------------------- ### Install @eggjs/bin Source: https://github.com/eggjs/egg/blob/next/tools/egg-bin/README.md Install the @eggjs/bin package as a development dependency. ```bash npm i @eggjs/bin --save-dev ``` -------------------------------- ### Install @eggjs/scripts Source: https://github.com/eggjs/egg/blob/next/tools/scripts/README.md Install the @eggjs/scripts package as a development dependency. ```bash npm i @eggjs/scripts --save ``` -------------------------------- ### Basic Router Setup with Koa Source: https://github.com/eggjs/egg/blob/next/packages/router/README.md Demonstrates the basic setup of a router with Koa. Ensure Koa and Router are imported before use. The router's routes and allowed methods must be used as middleware in the Koa app. ```typescript import Koa from '@eggjs/koa'; import Router from '@eggjs/router'; const app = new Koa(); const router = new Router(); router.get('/', async (ctx, next) => { // ctx.router available }); app.use(router.routes()).use(router.allowedMethods()); ``` -------------------------------- ### Install @eggjs/standalone Source: https://github.com/eggjs/egg/blob/next/tegg/standalone/standalone/README.md Install the @eggjs/standalone package using npm. ```sh npm i --save @eggjs/standalone ``` -------------------------------- ### Initialize Egg.js Project Source: https://github.com/eggjs/egg/wiki/How-to-create-a-new-repository Use egg-init to scaffold a new project, initialize a Git repository, and add a remote origin. ```bash $ egg-init --type=plugin egg-XXX $ cd egg-xxx && git init $ git remote add origin git@github.com:eggjs/egg-XXX.git ``` -------------------------------- ### Example ContextProto Services Source: https://github.com/eggjs/egg/blob/next/site/docs/zh-CN/basics/di.md Illustrates defining two services using ContextProto, one with a default name and another with a custom name. ```typescript // service.ts import { ContextProto } from 'egg'; @ContextProto() export class HelloService { async hello(): Promise { return 'hello'; } } @ContextProto({ name: 'worldInterface', }) export class WorldService { async world(): Promise { return 'world!'; } } ``` -------------------------------- ### Install @eggjs/redis Source: https://github.com/eggjs/egg/blob/next/plugins/redis/README.md Install the @eggjs/redis package using npm. ```bash npm i @eggjs/redis ``` -------------------------------- ### Install @eggjs/utils Source: https://github.com/eggjs/egg/blob/next/packages/utils/README.md Install the @eggjs/utils package using npm. ```bash npm i @eggjs/utils ``` -------------------------------- ### Async MySQL Plugin Initialization Source: https://github.com/eggjs/egg/blob/next/site/docs/advanced/plugin.md This example shows an asynchronous initialization function for a MySQL plugin, useful when configurations need to be fetched asynchronously. ```javascript async function createMysql(config, app) { // get mysql configurations asynchronous const mysqlConfig = await app.configManager.getMysqlConfig(config.mysql); assert(mysqlConfig.host && mysqlConfig.port && mysqlConfig.user && mysqlConfig.database); // create instance const client = new Mysql(mysqlConfig); // check before start the application const rows = await client.query('select now() as currentTime;'); app.coreLogger.info(`[egg-mysql] init instance success, rds currentTime: ${rows[0].currentTime}`); return client; } ``` -------------------------------- ### V8 Startup Snapshot for Faster Cold Starts Source: https://context7.com/eggjs/egg/llms.txt Use `buildSnapshot` and `restoreSnapshot` to pre-load application metadata into a V8 heap snapshot. This significantly reduces cold-start times, beneficial for serverless or short-lived container environments. ```typescript // snapshot_entry.ts (run with: node --snapshot-blob=snap.blob --build-snapshot snapshot_entry.ts) import { buildSnapshot } from 'egg'; await buildSnapshot({ baseDir: process.cwd(), env: 'prod' }); // server.ts (run with: node --snapshot-blob=snap.blob server.ts) import { restoreSnapshot, startCluster } from 'egg'; // Option A: single-process restore const app = await restoreSnapshot(); // All plugins, config, controllers, services are already loaded. // Normal lifecycle continues from configDidLoad. // Option B: restore and then attach to cluster // (handled internally when startCluster detects a snapshot blob) await startCluster({ baseDir: process.cwd(), snapshot: true }); ``` -------------------------------- ### Install @eggjs/cluster Source: https://github.com/eggjs/egg/blob/next/packages/cluster/README.md Install the @eggjs/cluster package using npm. ```bash npm i @eggjs/cluster ``` -------------------------------- ### Build and Deploy Source: https://github.com/eggjs/egg/blob/next/tools/create-egg/src/templates/simple-ts/README.md Compile TypeScript to JavaScript and start the application for deployment. ```bash npm run tsc npm start ``` -------------------------------- ### request.method Source: https://github.com/eggjs/egg/blob/next/packages/koa/docs/api/request.md Get the request method (e.g., GET, POST). ```APIDOC ## request.method ### Description Request method. ### Method GET ``` -------------------------------- ### Example SingletonProto Services Source: https://github.com/eggjs/egg/blob/next/site/docs/zh-CN/basics/di.md Illustrates defining two services using SingletonProto, one with a default name and another with a custom name. ```typescript // biz/HelloService.ts import { SingletonProto } from 'egg'; @SingletonProto() export class HelloService { async hello(): Promise { return 'hello'; } } @SingletonProto({ name: 'worldInterface', }) export class WorldService { async world(): Promise { return 'world!'; } } ``` -------------------------------- ### Perform a GET Request Source: https://github.com/eggjs/egg/blob/next/site/docs/core/httpclient.md Execute a GET request to fetch data. The default method is GET, so `options.method` is not required. The result object contains status, headers, and data. ```javascript // app/controller/npm.js class NpmController extends Controller { async get() { const ctx = this.ctx; const result = await ctx.curl('https://httpbin.org/get?foo=bar'); ctx.status = result.status; ctx.set(result.headers); ctx.body = result.data; } } ``` -------------------------------- ### mm.app(options) Source: https://github.com/eggjs/egg/blob/next/plugins/mock/README.md Creates a mock application instance for testing. It allows configuration of the base directory, framework, and other options. ```APIDOC ## mm.app(options) ### Description Creates a mock application instance for testing. It allows configuration of the base directory, framework, and other options. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Options - **baseDir** (String): The directory of the application. Defaults to `process.cwd()`. - **framework** (String/Boolean): The directory of the framework. Can be `true` when testing a framework. - **plugin** (Boolean): Set to `false` to prevent automatic plugin detection. - **plugins** (Object): Define a list of plugins. - **cache** (Boolean): Determines whether to enable caching. Defaults to true. - **clean** (Boolean): Cleans the logs directory. Defaults to true. ``` -------------------------------- ### Initialize Egg.js Project with Simple Boilerplate Source: https://github.com/eggjs/egg/blob/next/site/docs/tutorials/index.md Use this command to quickly set up a new Egg.js project with a simple boilerplate structure. This is useful for starting new applications with minimal configuration. ```bash $ npm init egg --type=simple ``` -------------------------------- ### Install @eggjs/typebox-validate Source: https://github.com/eggjs/egg/blob/next/plugins/typebox-validate/README.md Command to install the @eggjs/typebox-validate package using npm. ```bash npm i @eggjs/typebox-validate ``` -------------------------------- ### Create First Branch and Push Implementation Source: https://github.com/eggjs/egg/wiki/How-to-create-a-new-repository Create a new branch for your first implementation, add changes, commit, and push to the remote. ```bash $ git checkout -b first $ # do something $ git add . $ git commit -m 'feat: first implementation' $ git push ``` -------------------------------- ### Install @eggjs/tsconfig Source: https://github.com/eggjs/egg/blob/next/packages/tsconfig/README.md Install the package as a development dependency using npm. ```shell npm i --save-dev @eggjs/tsconfig ``` -------------------------------- ### Install @eggjs/tegg Source: https://github.com/eggjs/egg/blob/next/tegg/README.md Install the tegg annotation and plugin packages using npm. ```shell # tegg 注解 npm i --save @eggjs/tegg@beta # tegg 插件 npm i --save @eggjs/tegg-plugin@beta ``` -------------------------------- ### Install @eggjs/tegg and @eggjs/tegg-plugin Source: https://github.com/eggjs/egg/blob/next/tegg/core/tegg/README.md Use npm to install the necessary packages for @eggjs/tegg. ```sh npm i @eggjs/tegg @eggjs/tegg-plugin ``` -------------------------------- ### 配置集群监听 Source: https://github.com/eggjs/egg/blob/next/site/docs/zh-CN/core/deployment.md 在 `config/config.default.js` 中,可以通过 `exports.cluster.listen` 配置应用监听的端口、主机名或 Unix socket 路径。请注意,`egg-scripts` 和 `egg.startCluster` 传入的 `port` 参数优先级高于此配置。 ```javascript // config/config.default.js exports.cluster = { listen: { port: 7001, hostname: '127.0.0.1', // path: '/var/run/egg.sock', }, }; ``` -------------------------------- ### Install sequelize-cli Source: https://github.com/eggjs/egg/blob/next/site/docs/tutorials/sequelize.md Install the sequelize-cli tool as a development dependency using npm. ```bash npm install --save-dev sequelize-cli ``` -------------------------------- ### Install Dependencies for Standalone Mode Source: https://github.com/eggjs/egg/blob/next/tegg/plugin/ajv/README.md Install the necessary TeGG packages for standalone mode. ```shell npm i --save @eggjs/tegg npm i --save @eggjs/ajv-plugin ``` -------------------------------- ### Starting Egg.js Application with PM2 Command Source: https://github.com/eggjs/egg/blob/next/site/docs/community/faq.md Illustrates the command-line usage for starting an Egg.js application using PM2, assuming a `server.js` file is configured as shown in the related JavaScript snippet. ```bash pm2 start server.js ``` -------------------------------- ### Install and Run Egg.js Application Source: https://github.com/eggjs/egg/blob/next/README.md Follow these commands to quickly set up and run a new Egg.js application. Requires Node.js version 20.19.0 or higher. ```bash mkdir showcase && cd showcase pnpm create egg@beta pnpm install pnpm run dev open http://localhost:7001 ``` -------------------------------- ### Install Dependencies for Egg Mode Source: https://github.com/eggjs/egg/blob/next/tegg/plugin/ajv/README.md Install the necessary TeGG packages for Egg.js mode. ```shell npm i --save @eggjs/tegg npm i --save @eggjs/tegg-plugin npm i --save @eggjs/ajv-plugin ``` -------------------------------- ### Initiate Framework Test with Mock App Source: https://github.com/eggjs/egg/blob/next/site/docs/advanced/framework.md Use `mock.app` to create an application instance for framework testing. Ensure `framework: true` is set and wait for the `app.ready()` event before making requests. Remember to close the app and restore mocks after each test. ```javascript const mock = require('@eggjs/mock'); describe('test/index.test.js', () => { let app; before(() => { app = mock.app({ // test/fixtures/apps/example baseDir: 'apps/example', // importent !! Do not miss framework: true, }); return app.ready(); }); after(() => app.close()); afterEach(mock.restore); it('should success', () => { return app.httpRequest().get('/').expect(200); }); }); ``` -------------------------------- ### Install @eggjs/orm-decorator Source: https://github.com/eggjs/egg/blob/next/tegg/core/orm-decorator/README.md Install the package using npm. This is the first step before defining models. ```shell npm i --save @eggjs/orm-decorator ``` -------------------------------- ### Custom Environment Example (SIT) Source: https://github.com/eggjs/egg/blob/next/site/docs/basics/env.md Customize the development process by setting `EGG_SERVER_ENV` to a custom value like 'sit'. This will load `config/config.sit.js` and set `app.config.env` to 'sit'. It's recommended to also set `NODE_ENV = production` in this scenario. ```javascript // Example: Setting EGG_SERVER_ENV to 'sit' // NODE_ENV = production // Framework will load config/config.sit.js // app.config.env will be 'sit' ``` -------------------------------- ### Install Testing Dependencies Source: https://github.com/eggjs/egg/blob/next/site/docs/intro/quickstart.md Install `egg-mock` as a development dependency for writing unit tests. ```bash npm i egg-mock --save-dev ``` -------------------------------- ### Create Testcase with mm.app Source: https://github.com/eggjs/egg/blob/next/plugins/mock/README.md Launch a mock server using mm.app for testing application requests. Ensure the application is ready before making requests and close it after tests. ```javascript // test/index.test.js const path = require('node:path'); const mm = require('@eggjs/mock'); describe('some test', () => { let app; before(() => { app = mm.app({ baseDir: 'apps/foo', }); return app.ready(); }); after(() => app.close()); it('should request /', () => { return app.httpRequest().get('/').expect(200); }); }); ``` -------------------------------- ### Kick out User Example Source: https://github.com/eggjs/egg/blob/next/site/docs/tutorials/socketio.md Example of how to remotely disconnect a specific client using its ID. ```javascript const tick = (id, msg) => { logger.debug('# tick', id, msg); socket.emit(id, msg); app.io.of('/').adapter.remoteDisconnect(id, true, (err) => { logger.error(err); }); }; ``` -------------------------------- ### Install Egg-Sequelize and MySQL2 Source: https://github.com/eggjs/egg/blob/next/site/docs/tutorials/sequelize.md Install the necessary npm packages for Sequelize integration and MySQL connectivity. ```bash npm install --save egg-sequelize mysql2 ```