### GET /hello Source: https://www.midwayjs.org/docs/3.0.0/hooks/api Example of creating a GET endpoint with a custom path using the Api() and Get() functions. ```APIDOC ## [GET] /hello ### Description Creates a GET endpoint at the specified path '/hello'. ### Method GET ### Endpoint /hello ### Parameters None ### Request Example None ### Response #### Success Response (200) - **body** (string) - The response body is 'Hello World!'. #### Response Example "Hello World!" ``` -------------------------------- ### Start Node service with ENABLE_NODE_LOG=YES Source: https://www.midwayjs.org/docs/3.0.0/extensions/alinode When starting the Node service on the server, include the ENABLE_NODE_LOG=YES environment variable to enable logging for Alinode. Example uses NODE_ENV=production. ```bash $ NODE_ENV=production ENABLE_NODE_LOG=YES node bootstrap.js ``` -------------------------------- ### GET /api/hello Source: https://www.midwayjs.org/docs/3.0.0/hooks/api Example of creating a GET endpoint using the Api() and Get() functions from @midwayjs/hooks. ```APIDOC ## [GET] /api/hello ### Description Creates a GET endpoint that returns 'Hello World!'. ### Method GET ### Endpoint /api/hello ### Parameters None ### Request Example None ### Response #### Success Response (200) - **body** (string) - The response body is 'Hello World!'. #### Response Example "Hello World!" ``` -------------------------------- ### GET /api/hello (with context) Source: https://www.midwayjs.org/docs/3.0.0/hooks/api Example of using useContext to access the request context and return the method and path. ```APIDOC ## [GET] /api/hello (with context) ### Description Creates a GET endpoint that uses the request context to return the HTTP method and path. ### Method GET ### Endpoint /api/hello ### Parameters None ### Request Example None ### Response #### Success Response (200) - **method** (string) - The HTTP method of the request. - **path** (string) - The path of the request. #### Response Example { "method": "GET", "path": "/api/hello" } ``` -------------------------------- ### Start application with egg-scripts Source: https://www.midwayjs.org/docs/3.0.0/extensions/egg Example of starting the application with egg-scripts. Supports parameters like --port, --daemon, --env, --workers, --title, --framework, --ignore-stderr, --https.key, and --https.cert. Logs are stored in the user's home directory. ```bash $ egg-scripts start --port=7001 --daemon --title=egg-server-showcase ``` -------------------------------- ### Complete test example with createApp, close, and createHttpRequest Source: https://www.midwayjs.org/docs/3.0.0/testing A full test file example showing how to set up and tear down an app, and test GET and POST endpoints using both Jest expect and Node assert. ```typescript import { createApp, close, createHttpRequest } from '@midwayjs/mock'; import { Framework, Application } from '@midwayjs/koa'; import * as assert from 'assert'; describe('test/controller/home.test.ts', () => { let app: Application; beforeAll(async () => { // 只创建一次 app,可以复用 app = await createApp(); }); afterAll(async () => { // close app await close(app); }); it('should GET /', async () => { // make request const result = await createHttpRequest(app) .get('/') .set('x-timeout', '5000'); // use expect by jest expect(result.status).toBe(200); expect(result.text).toBe('Hello Midwayjs!'); // or use assert assert.deepStrictEqual(result.status, 200); assert.deepStrictEqual(result.text, 'Hello Midwayjs!'); }); it('should POST /', async () => { // make request const result = await createHttpRequest(app) .post('/') .send({id: '1'}); // use expect by jest expect(result.status).toBe(200); }); }); ``` -------------------------------- ### Install @midwayjs/jwt and passport-jwt Source: https://www.midwayjs.org/docs/3.0.0/extensions/passport Install the required dependencies for the JWT strategy example. ```bash $ npm i @midwayjs/jwt passport-jwt --save ``` -------------------------------- ### GET /api/hello (set header) Source: https://www.midwayjs.org/docs/3.0.0/hooks/api Example of setting a response header using the context object. ```APIDOC ## [GET] /api/hello (set header) ### Description Creates a GET endpoint that sets a custom response header using the context. ### Method GET ### Endpoint /api/hello ### Parameters None ### Request Example None ### Response #### Success Response (200) - **X-Powered-By** (string) - The header set to 'Midway'. - **body** (string) - The response body is 'Hello World!'. #### Response Example Headers: X-Powered-By: Midway Body: "Hello World!" ``` -------------------------------- ### Version compatibility mapping example for @midwayjs/version Source: https://www.midwayjs.org/docs/3.0.0/how_to_update_midway Example version mapping file from the @midwayjs/version package. Filenames follow `decoratorVersion-coreVersion.json`; each key maps to a compatible version or array of compatible versions. If a filename is missing or versions don't match, the version setup may be broken. ```json { "@midwayjs/egg-layer": [ "2.10.18", "2.10.19" ], "@midwayjs/express-layer": "2.10.18", "@midwayjs/faas-typings": "2.10.7", "@midwayjs/koa-layer": "2.10.18", "@midwayjs/runtime-engine": "2.10.14", "@midwayjs/runtime-mock": "2.10.14", "@midwayjs/serverless-app": "2.10.18", "@midwayjs/serverless-aws-starter": "2.10.14", "@midwayjs/serverless-fc-starter": "2.10.18", "@midwayjs/serverless-fc-trigger": "2.10.18", "@midwayjs/serverless-http-parser": "2.10.7", "@midwayjs/serverless-scf-starter": "2.10.14", "@midwayjs/serverless-scf-trigger": "2.10.18", "@midwayjs/static-layer": "2.10.18", "@midwayjs/bootstrap": "2.10.18", "@midwayjs/cache": "2.10.18", "@midwayjs/consul": "2.10.18", "@midwayjs/core": "2.10.18", "@midwayjs/decorator": "2.10.18", "@midwayjs/faas": "2.10.18", "@midwayjs/grpc": "2.10.18", "@midwayjs/logger": "2.10.18", "midway-schedule": "2.10.18", "midway": [ "2.10.18", "2.10.19" ], "@midwayjs/mock": "2.10.18", "@midwayjs/prometheus": "2.10.18", "@midwayjs/rabbitmq": "2.10.18", "@midwayjs/socketio": "2.10.18", "@midwayjs/task": [ "2.10.18", "2.10.19" ], "@midwayjs/typegoose": "2.10.18", "@midwayjs/version": [ "2.10.18", "2.10.19" ], "@midwayjs/express": "2.10.18", "@midwayjs/koa": "2.10.18", "@midwayjs/web": [ "2.10.18", "2.10.19" ] } ``` -------------------------------- ### Install dependencies for binary deployment Source: https://www.midwayjs.org/docs/3.0.0/deployment Install the required dependencies for binary deployment: @midwayjs/bundle-helper to generate the entry file, and pkg to build the binary. The pkg package can be installed globally or locally (recommended). ```bash ## 用于生成入口 $ npm i @midwayjs/bundle-helper --save-dev ## 用于构建二进制文件 ## 装到全局 $ npm i pkg -g ## 或者装到项目(推荐) $ npm i pkg --save-dev ``` -------------------------------- ### Install Serverless Devs tool globally Source: https://www.midwayjs.org/docs/3.0.0/serverless/aliyun_faas Install the Serverless Devs CLI globally using npm. After installation, configure credentials as per the referenced documentation. ```bash $ npm install @serverless-devs/s -g ``` -------------------------------- ### Install opentelemetry-arms SDK Source: https://www.midwayjs.org/docs/3.0.0/extensions/otel Installs the opentelemetry-arms SDK for Alibaba Cloud ARMS integration. ```bash # arms sdk $ npm install --save opentelemetry-arms ``` -------------------------------- ### Install @midwayjs/grpc and @midwayjs/grpc-helper Source: https://www.midwayjs.org/docs/3.0.0/extensions/grpc Install the required gRPC dependencies for Midway. The first command installs the main gRPC module, and the second installs the helper package as a development dependency. ```bash $ npm i @midwayjs/grpc@3 --save $ npm i @midwayjs/grpc-helper --save-dev ``` -------------------------------- ### Example .env file Source: https://www.midwayjs.org/docs/3.0.0/env_config Example .env file content with secret keys. ```plaintext OSS_SECRET=12345 OSS_ACCESSKEY=54321 ``` -------------------------------- ### Install @midwayjs/tenant via npm Source: https://www.midwayjs.org/docs/3.0.0/extensions/tenant Install the @midwayjs/tenant package version 3 using npm. ```bash $ npm i @midwayjs/tenant@3 --save ``` -------------------------------- ### Install upload dependencies Source: https://www.midwayjs.org/docs/3.0.0/hooks/upload Install the required packages for file upload in a Midway Hooks project. ```bash npm install @midwayjs/upload @midwayjs/hooks-upload ``` -------------------------------- ### Install @midwayjs/static-file Source: https://www.midwayjs.org/docs/3.0.0/extensions/static_file Install the @midwayjs/static-file component for Midway 3.x. ```bash $ npm i @midwayjs/static-file@3 --save ``` -------------------------------- ### Install database drivers Source: https://www.midwayjs.org/docs/3.0.0/extensions/sequelize Install the appropriate database driver for your database type. ```bash # for MySQL or MariaDB,也可以使用 mysql2 替代 npm install mysql --save npm install mysql2 --save # for PostgreSQL or CockroachDB npm install pg --save # for SQLite npm install sqlite3 --save # for Microsoft SQL Server npm install mssql --save # for sql.js npm install sql.js --save # for Oracle npm install oracledb --save # for MongoDB(experimental) npm install mongodb --save ``` -------------------------------- ### Call gRPC service using grpcClients Source: https://www.midwayjs.org/docs/3.0.0/extensions/grpc Call a gRPC service by retrieving a client instance with `grpcClients.getService` and invoking a method. This example gets 'helloworld.Greeter' and calls `sayHello` with a message containing 'harry'. The result is returned. ```typescript import { Provide, Inject, } from '@midwayjs/core'; import { helloworld, hero } from '../interface'; import { Clients } from '@midwayjs/grpc'; @Provide() export class UserService { @Inject() grpcClients: Clients; async invoke() { // 获取服务 const greeterService = this.grpcClients.getService( 'helloworld.Greeter' ); // 调用服务 const result = await greeterService.sayHello() .sendMessage({ name: 'harry' }); // 返回结果 return result; } } ``` -------------------------------- ### Install tnvm, alinode, and agenthub Source: https://www.midwayjs.org/docs/3.0.0/extensions/alinode Install the Node.js performance platform components: tnvm version manager, alinode (replacing default node), and the data collector agenthub. After installation, ensure 'which node' and 'which agenthub' include '.tnvm' in their paths. ```bash # 安装版本管理工具 tnvm,安装过程出错参考:https://github.com/aliyun-node/tnvm $ wget -O- https://raw.githubusercontent.com/aliyun-node/tnvm/master/install.sh | bash $ source ~/.bashrc # tnvm ls-remote alinode # 查看需要的版本 $ tnvm install alinode-v6.5.0 # 安装需要的版本 $ tnvm use alinode-v6.5.0 # 使用需要的版本 $ npm install @alicloud/agenthub -g # 安装 agenthub ``` -------------------------------- ### Install @midwayjs/otel Source: https://www.midwayjs.org/docs/3.0.0/extensions/otel Install the @midwayjs/otel component version 3. ```bash $ npm i @midwayjs/otel@3 --save ``` -------------------------------- ### Start bundled application Source: https://www.midwayjs.org/docs/3.0.0/deployment Start the built single-file application in production mode. If startup and access are successful, the build directory can be distributed. ```bash $ npm run bundle_start ``` -------------------------------- ### Install @midwayjs/redis via npm Source: https://www.midwayjs.org/docs/3.0.0/extensions/redis Install the Redis component package using npm. ```bash $ npm i @midwayjs/redis@3 --save ``` -------------------------------- ### Install @midwayjs/socketio and client dependencies Source: https://www.midwayjs.org/docs/3.0.0/extensions/socketio Install the Socket.io component and optional client dependencies for a Midway project. ```bash $ npm i @midwayjs/socketio@3 --save ## 客户端可选 $ npm i @types/socket.io-client socket.io-client --save-dev ``` -------------------------------- ### Install @midwayjs/security Source: https://www.midwayjs.org/docs/3.0.0/extensions/security Install the @midwayjs/security package using npm. ```bash $ npm i @midwayjs/security --save ``` -------------------------------- ### Install @socket.io/redis-adapter Source: https://www.midwayjs.org/docs/3.0.0/extensions/socketio Install the @socket.io/redis-adapter package, which is the updated adapter package name (formerly socket.io-redis). ```bash $ npm i @socket.io/redis-adapter --save ``` -------------------------------- ### 构建 Docker 镜像 Source: https://www.midwayjs.org/docs/3.0.0/deployment 使用 docker build 命令构建镜像,镜像名为 helloworld。 ```bash $ docker build -t helloworld . ``` -------------------------------- ### Install @midwayjs/prometheus-socket-io Source: https://www.midwayjs.org/docs/3.0.0/extensions/prometheus Install the @midwayjs/prometheus-socket-io package for Socket.io metrics in MidwayJS. ```bash $ npm install @midwayjs/prometheus-socket-io@3 --save ``` -------------------------------- ### Install Jaeger Exporter Dependencies Source: https://www.midwayjs.org/docs/3.0.0/extensions/otel Installs the Jaeger exporter and propagator packages required for the Jaeger Exporter example. ```bash $ npm install --save @opentelemetry/exporter-jaeger @opentelemetry/propagator-jaeger ``` -------------------------------- ### Install MQTT component via npm Source: https://www.midwayjs.org/docs/3.0.0/extensions/mqtt Install the @midwayjs/mqtt component using npm. Requires Node.js >= 16. ```bash $ npm i @midwayjs/mqtt@3 --save ``` -------------------------------- ### Set, get, and reset cache data Source: https://www.midwayjs.org/docs/3.0.0/extensions/cache Example service showing how to set, get, and reset cache data using the CacheManager API. ```typescript import { Inject, Provide } from '@midwayjs/core'; import { IUserOptions } from '../interface'; import { CacheManager } from '@midwayjs/cache'; @Provide() export class UserService { @Inject() cacheManager: CacheManager; async getUser(options: IUserOptions) { // 设置缓存内容 await this.cacheManager.set(`name`, 'stone-jin'); // 获取缓存内容 let result = await this.cacheManager.get(`name`); return result; } async getUser2(){ //获取缓存内容 let result = await this.cacheManager.get(`name`); return result; } async reset(){ await this.cacheManager.reset(); // 清空对应 store 的内容 } } ``` -------------------------------- ### 默认行为:列出模板列表 Source: https://www.midwayjs.org/docs/3.0.0/tool/create_midway 执行 npm init midway 后,会显示可选的模板列表,用户选择后按指引创建模板。 ```bash $ npm init midway@latest -y ``` ```text ➜ ~ npm init midway ? Hello, traveller. Which template do you like? … ⊙ v3 ❯ koa-v3 - A web application boilerplate with midway v3(koa) egg-v3 - A web application boilerplate with midway v3(egg 2.0) faas-v3 - A serverless application boilerplate with midway v3(faas) component-v3 - A midway component boilerplate for v3 quick-start - A midway quickstart exmaple for v3 ⊙ v3-esm koa-v3-esm - A web application boilerplate with midway v3(koa) ⊙ v2 web - A web application boilerplate with midway and Egg.js koa - A web application boilerplate with midway and koa ``` -------------------------------- ### Annotated helloworld.proto with comments Source: https://www.midwayjs.org/docs/3.0.0/extensions/grpc The same `helloworld.proto` file with Chinese comments explaining the service, request, and response definitions. This is the version used for the subsequent demonstration. ```protobuf syntax = "proto3"; package helloworld; // 服务的定义 service Greeter { // Sends a greeting rpc SayHello (HelloRequest) returns (HelloReply) {} } // 服务的请求参数 message HelloRequest { string name = 1; } // 服务的响应参数 message HelloReply { string message = 1; } ``` -------------------------------- ### Get instances in Express middleware Source: https://www.midwayjs.org/docs/3.0.0/container Express middleware example showing how to get instances from the request-scoped container using req.requestContext. Use this when working with Express. ```typescript import { UserService, Middleware } from './service/user'; import { NextFunction, Context, Response } from '@midwayjs/express'; @Middleware() export class ReportMiddleware implements IMiddleware { resolve() { return async (req, res, next) => { const userService = await req.requestContext.getAsync(UserService); // ... next(); } } } ``` -------------------------------- ### Install @midwayjs/tablestore via npm Source: https://www.midwayjs.org/docs/3.0.0/extensions/tablestore Install the @midwayjs/tablestore package version 3 using npm. ```bash $ npm i @midwayjs/tablestore@3 --save ``` -------------------------------- ### Get data source via TypeORMDataSourceManager Source: https://www.midwayjs.org/docs/3.0.0/extensions/orm Gets a DataSource object by injecting the TypeORMDataSourceManager and calling getDataSource('default'). The example also checks connectivity with isConnected. ```typescript import { Configuration } from '@midwayjs/core'; import { TypeORMDataSourceManager } from '@midwayjs/typeorm'; @Configuration({ // ... }) export class MainConfiguration { async onReady(container: IMidwayContainer) { const dataSourceManager = await container.getAsync(TypeORMDataSourceManager); const conn = dataSourceManager.getDataSource('default'); console.log(dataSourceManager.isConnected(conn)); } } ``` -------------------------------- ### Start agenthub with yourconfig.json Source: https://www.midwayjs.org/docs/3.0.0/extensions/alinode Launch the Alinode agent using the configuration file created earlier. This starts the data collector for the Node.js performance platform. ```bash agenthub start yourconfig.json ``` -------------------------------- ### Create a basic GET API with Api() and Get() Source: https://www.midwayjs.org/docs/3.0.0/hooks/api Defines a GET endpoint at /api/hello by default. The Api() function wraps an async handler that returns 'Hello World!'. The path is generated from function and file name with /api prefix. ```typescript import { Api, Get, } from '@midwayjs/hooks'; export default Api( Get(), // Http Path: /api/hello, async () => { return 'Hello World!'; } ); ``` -------------------------------- ### Install @midwayjs/sequelize and dependencies Source: https://www.midwayjs.org/docs/3.0.0/extensions/sequelize Install the required npm packages for using Sequelize with Midway. ```bash $ npm i @midwayjs/sequelize@3 sequelize sequelize-typescript --save ``` -------------------------------- ### Install @midwayjs/code-dye via npm Source: https://www.midwayjs.org/docs/3.0.0/extensions/code_dye Install the code-dye component version 3 using npm. ```bash $ npm i @midwayjs/code-dye@3 --save ``` -------------------------------- ### Default query array parsing example Source: https://www.midwayjs.org/docs/3.0.0/extensions/koa Example of a GET request with array-like query parameters and the default parsed result using querystring, which splits array data into separate keys. ```http GET /query?a[0]=1&a[1]=2 ``` ```json { "a[0]": 1, "a[1]": 2, } ``` -------------------------------- ### Build binary with bundle and pkg Source: https://www.midwayjs.org/docs/3.0.0/deployment Run the build commands: first npm run bundle to generate the entry file and build the TypeScript files, then npm run pkg to create the platform-specific binary. The resulting executable appears in the build directory. ```bash $ npm run bundle $ npm run pkg ``` -------------------------------- ### Install @midwayjs/cross-domain Source: https://www.midwayjs.org/docs/3.0.0/extensions/cross_domain Install the cross-domain component package for MidwayJS frameworks. ```bash $ npm i @midwayjs/cross-domain --save ``` -------------------------------- ### Install dependencies for single-file build Source: https://www.midwayjs.org/docs/3.0.0/deployment Install the required dependencies for single-file builds: @midwayjs/bundle-helper for generating the entry file and @vercel/ncc for bundling. The ncc package can be installed globally or as a project dev dependency (recommended). ```bash ## 用于生成入口 $ npm i @midwayjs/bundle-helper --save-dev ## 用于构建单文件 ## 装到全局 $ npm i @vercel/ncc -g ## 或者装到项目(推荐) $ npm i @vercel/ncc --save-dev ``` -------------------------------- ### Project directory structure Source: https://www.midwayjs.org/docs/3.0.0/container Directory structure for the dependency injection example, showing the controller and service files under src. ```text . ├── package.json ├── src │ ├── controller # 控制器目录 │ │ └── user.controller.ts │ └── service # 服务目录 │ └── user.service.ts └── tsconfig.json ``` -------------------------------- ### Get instances in Koa middleware Source: https://www.midwayjs.org/docs/3.0.0/container Koa middleware example showing how to use the container API to get instances inside middleware. Demonstrates both generic and inferred types, and the request-scoped container. ```typescript import { Middleware, ApplicationContext, IMiddleware } from '@midwayjs/core'; import { NextFunction, Context } from '@midwayjs/koa'; import { UserService } from './service/user.service'; @Middleware() export class ReportMiddleware implements IMiddleware { @ApplicationContext() applicationContext: IMidwayContainer; resolve() { return async(ctx, next) => { // 指定泛型类型,比如某个接口 const userService1 = await this.applicationContext.getAsync(UserService); // 不写泛型,也能推导出正确的类型 const userService1 = await this.applicationContext.getAsync(UserService); // 下面的方法获取的服务和请求关联,可以注入上下文 const userService2 = await ctx.requestContext.getAsync(UserService); await next(); } } } ``` -------------------------------- ### Install dotenv Source: https://www.midwayjs.org/docs/3.0.0/env_config Install the dotenv package to load environment variables from a .env file. ```bash $ npm i dotenv --save ``` -------------------------------- ### Start Midway dev server and open browser Source: https://www.midwayjs.org/docs/3.0.0/quickstart Starts the Midway HTTP server and opens the browser. Accessing http://127.0.0.1:7001 prints 'Hello midwayjs!'. ```bash $ npm run dev $ open http://localhost:7001 ``` -------------------------------- ### Basic helloworld.proto definition Source: https://www.midwayjs.org/docs/3.0.0/extensions/grpc A basic `proto/helloworld.proto` file defining the `Greeter` service with a `SayHello` RPC. Uses proto3 syntax and defines `HelloRequest` and `HelloReply` messages. ```protobuf syntax = "proto3"; package helloworld; service Greeter { // Sends a greeting rpc SayHello (HelloRequest) returns (HelloReply) {} } message HelloRequest { string name = 1; } message HelloReply { string message = 1; } ``` -------------------------------- ### Get header parameter with @Headers() decorator Source: https://www.midwayjs.org/docs/3.0.0/controller Use this snippet to retrieve a request header value in a MidwayJS controller. The @Headers('cache-control') decorator injects the 'cache-control' header value. The example shows a GET endpoint that uses the decorator to access the header. ```typescript // src/controller/user.ts // GET /user/1 import { Controller, Get, Headers } from '@midwayjs/core'; @Controller('/user') export class UserController { @Get('/:uid') async getUser(@Headers('cache-control') cacheSetting: string): Promise { // no-cache // ... } } ``` -------------------------------- ### Get App Instance with getApp Source: https://www.midwayjs.org/docs/3.0.0/req_res_app Retrieves the current framework's app object from the context. The comment shows an example of calling app.getConfig(). ```typescript const app = this.ctx.getApp(); // app.getConfig(); ``` -------------------------------- ### InitDataMock 模拟类(添加中间件) Source: https://www.midwayjs.org/docs/3.0.0/mock 在 appSetup 中根据框架类型(koa、bull)添加不同的中间件和过滤器。 ```typescript import { App, IMidwayApplication, Mock, ISimulation } from '@midwayjs/core'; @Mock() export class InitDataMock implements ISimulation { @App() app: IMidwayApplication; async appSetup(app: IMidwayApplication): Promise { // 针对不同的框架类型,添加不同的测试中间件 if (app.getNamespace() === 'koa') { app.useMiddleware(/*...*/); app.useFilter(/*...*/); } if (app.getNamespace() === 'bull') { app.useMiddleware(/*...*/); app.useFilter(/*...*/); } } enableCondition(): boolean | Promise { return ['local', 'test', 'unittest'].includes(this.app.getEnv()); } } ``` -------------------------------- ### Install @midwayjs/cache and cache-manager Source: https://www.midwayjs.org/docs/3.0.0/extensions/cache Install the Midway Cache component and its type definitions using npm. ```bash $ npm i @midwayjs/cache@3 cache-manager --save $ npm i @types/cache-manager --save-dev ``` -------------------------------- ### Manually execute a job after startup Source: https://www.midwayjs.org/docs/3.0.0/extensions/bull Shows how to get the 'test' queue and add a job to it immediately after the application starts, using the bullFramework injection. ```typescript import { Configuration, Inject } from '@midwayjs/core'; import * as bull from '@midwayjs/bull'; @Configuration({ imports: [ // ... bull ] }) export class MainConfiguration { @Inject() bullFramework: bull.Framework; //... async onServerReady() { // 获取 Processor 相关的队列 const testQueue = this.bullFramework.getQueue('test'); // 立即添加这个任务 await testQueue?.addJobToQueue(); } } ``` -------------------------------- ### Create HTTP client instance and configuration Source: https://www.midwayjs.org/docs/3.0.0/service_factory Shows how to create a client configuration object and instantiate an HTTP client with it. This is the initial example for the service factory scenario. ```typescript // 创建客户端的配置 const config = { baseUrl: '', timeout: 1000, }; // 创建客户端实例的方法 const httpClient = new HTTPClient(config); ``` -------------------------------- ### Install @midwayjs/info via npm Source: https://www.midwayjs.org/docs/3.0.0/extensions/info Installs the Midway info component version 3 for standard projects. ```bash $ npm i @midwayjs/info@3 --save ``` -------------------------------- ### Get route parameter with @Param() decorator Source: https://www.midwayjs.org/docs/3.0.0/controller Use this snippet to retrieve a route parameter in a MidwayJS controller. The @Param('uid') decorator injects the 'uid' parameter from the URL path, equivalent to ctx.params.uid. The example shows a GET endpoint with a dynamic route segment. ```typescript // src/controller/user.ts // GET /user/1 import { Controller, Get, Param } from '@midwayjs/core'; @Controller('/user') export class UserController { @Get('/:uid') async getUser(@Param('uid') uid: string): Promise { // xxxx } } ``` -------------------------------- ### Get route parameter from context API Source: https://www.midwayjs.org/docs/3.0.0/controller Use this snippet to retrieve route parameters via the context object in a MidwayJS controller. The @Inject() decorator injects the Context, and this.ctx.params provides the route parameters. The example shows a GET endpoint with a dynamic route segment. ```typescript // src/controller/user.ts // GET /user/1 import { Controller, Get, Inject } from '@midwayjs/core'; import { Context } from '@midwayjs/koa'; @Controller('/user') export class UserController { @Inject() ctx: Context; @Get('/:uid') async getUser(): Promise { const params = this.ctx.params; // { // uid: '1', // } } } ``` -------------------------------- ### hooks build --help 输出 Source: https://www.midwayjs.org/docs/3.0.0/hooks/fullstack `hooks build --help` 命令的输出,显示构建命令的用法和选项。 ```text Usage: $ hooks build [root] Options: --outDir [string] output directory (default: dist) --clean [boolean] clean output directory before build (default: false) -h, --help Display this message ``` -------------------------------- ### Install Redis watcher dependencies Source: https://www.midwayjs.org/docs/3.0.0/extensions/casbin Install the required packages for the Redis watcher: the adapter and the Redis component. ```bash $ npm i @midwayjs/casbin-redis-adapter @midwayjs/redis --save ``` -------------------------------- ### Project directory structure Source: https://www.midwayjs.org/docs/3.0.0/extensions/rabbitmq Example directory structure for a Midway project with a consumer directory. Place consumer files in src/consumer. ```bash ➜ my_midway_app tree . ├── src │ ├── consumer │ │ └── user.consumer.ts │ ├── interface.ts │ └── service │ └── user.service.ts ├── test ├── package.json └── tsconfig.json ``` -------------------------------- ### Get Custom Logger with getLogger Source: https://www.midwayjs.org/docs/3.0.0/req_res_app Fetches a custom logger by name from the context. The example shows a comment indicating the returned logger is named 'custom'. ```typescript this.ctx.getLogger('custom'); // => custom logger ``` -------------------------------- ### Get Request-Scoped Data with getAttr Source: https://www.midwayjs.org/docs/3.0.0/req_res_app Retrieves data previously stored with setAttr. The example logs the retrieved object, which outputs { a: 1, b: 2 }. ```typescript const value = this.ctx.getAttr('abc'); console.log(value); // { a: 1, b: 2 } ``` -------------------------------- ### Package and deploy with --function option Source: https://www.midwayjs.org/docs/3.0.0/tool/cli Examples of using the `--function` option to specify which functions to package and deploy. Multiple functions are separated by commas. ```bash // 打包 midway-bin package --function=a,b,c // 发布 midway-bin deploy --function=a,b,c ``` -------------------------------- ### Get container in Configuration onReady Source: https://www.midwayjs.org/docs/3.0.0/container In the configuration lifecycle method onReady, the dependency injection container is passed as a parameter. Use it directly for setup tasks. ```typescript // src/configuration.ts import { Configuration, IMidwayContainer } from '@midwayjs/core'; @Configuration() export class MainConfiguration { async onReady(applicationContext: IMidwayContainer) { // ... } } ``` -------------------------------- ### Example: host proxy configuration Source: https://www.midwayjs.org/docs/3.0.0/extensions/http-proxy Example of using the host option to replace the request host with https://gw.alicdn.com when the path matches /tfs/. ```typescript export default { httpProxy: { match: /\/tfs\//, host: 'https://gw.alicdn.com', }, }; ``` -------------------------------- ### Install Express adapter dependencies Source: https://www.midwayjs.org/docs/3.0.0/extensions/express Install the Express adapter and its type definitions for Midway. Use this command in a Midway project to add Express support. ```bash $ npm i @midwayjs/express@3 --save $ npm i @types/body-parser @types/express @types/express-session --save-dev ``` -------------------------------- ### Set and get cookies with ctx.cookies in @midwayjs/koa Source: https://www.midwayjs.org/docs/3.0.0/cookie_session Use this snippet in a MidwayJS Koa controller to set and get cookies via the context. The example sets a cookie named 'foo' with value 'bar' and the 'encrypt' option, then retrieves it with the same option. This is the default cookie API provided by @midwayjs/koa. ```typescript import { Inject, Controller, Get, Provide } from '@midwayjs/core'; import { Context } from '@midwayjs/koa'; @Controller('/') export class HomeController { @Inject() ctx: Context; @Get('/') async home() { // set cookie this.ctx.cookies.set('foo', 'bar', { encrypt: true }); // get cookie this.ctx.cookies.get('foo', { encrypt: true }); } } ``` -------------------------------- ### Get main app with getCurrentMainApp Source: https://www.midwayjs.org/docs/3.0.0/container Use to obtain the main framework's app object after startup, for example to access global configuration via getConfig(). ```typescript import { getCurrentMainApp } from '@midwayjs/core'; export const getGlobalConfig = () => { return getCurrentMainApp().getConfig(); } ``` -------------------------------- ### Run a transaction with dataSource.transaction Source: https://www.midwayjs.org/docs/3.0.0/extensions/orm Starts a transaction by getting the data source and calling dataSource.transaction. Inside the callback, use transactionalEntityManager to run operations like save. ```typescript import { Provide, Inject } from '@midwayjs/core'; import { TypeORMDataSourceManager } from '@midwayjs/typeorm'; import { UserDTO } from '../entity/user'; @Provide() export class UserService { @Inject() dataSourceManager: TypeORMDataSourceManager; async updateUser(user: UserDTO) { // get dataSource const dataSource = this.dataSourceManager.getDataSource('default'); // start transaction await dataSource.transaction(async (transactionalEntityManager) => { // run code await transactionalEntityManager.save(UserDTO, user); }); } } ``` -------------------------------- ### 启动 docker-compose 服务 Source: https://www.midwayjs.org/docs/3.0.0/extensions/prometheus 使用 docker-compose up 启动 Prometheus 服务,开始拉取 Node 应用的指标数据。 ```bash $ docker-compose up ``` -------------------------------- ### Get HTTP server with framework.getServer() Source: https://www.midwayjs.org/docs/3.0.0/extensions/koa Retrieves the underlying HTTP server after the server has started by injecting the Koa framework and calling getServer() in the onServerReady lifecycle hook. ```typescript import { App, Configuration } from '@midwayjs/core'; import * as koa from '@midwayjs/koa'; @Configuration({ // ... }) export class MainConfiguration { @Inject() framework: koa.Framework; async onServerReady(container) { const server = this.framework.getServer(); // ... } } ``` -------------------------------- ### Define ICacheService interface and implementations Source: https://www.midwayjs.org/docs/3.0.0/container Defines an interface and two implementations (local and remote) that a factory method can return. This is the setup for the dynamic factory injection example. ```typescript export interface ICacheService { getData(): any; } @Provide() export class LocalCacheService implements ICacheService { async getData {} } @Provide() export class RemoteCacheService implements ICacheService { async getData {} } ``` -------------------------------- ### Get header parameter from context API Source: https://www.midwayjs.org/docs/3.0.0/controller Use this snippet to retrieve a request header value via the context object in a MidwayJS controller. The @Inject() decorator injects the Context, and this.ctx.get('cache-control') retrieves the header value. The example shows a GET endpoint that uses the context API. ```typescript // src/controller/user.ts // GET /user/1 import { Controller, Get, Inject } from '@midwayjs/core'; import { Context } from '@midwayjs/koa'; @Controller('/user') export class UserController { @Inject() ctx: Context; @Get('/:uid') async getUser(): Promise { const cacheSetting = this.ctx.get('cache-control'); // no-cache } } ``` -------------------------------- ### Default public directory structure Source: https://www.midwayjs.org/docs/3.0.0/extensions/static_file Example project structure showing the default public directory. ```text ➜ my_midway_app tree . ├── src ├── public | ├── index.html │ └── hello.js │ ├── test ├── package.json └── tsconfig.json ``` -------------------------------- ### Hello World API endpoint Source: https://www.midwayjs.org/docs/3.0.0/hooks/test Defines a simple GET endpoint at /hello that returns 'Hello World!'. This is the backend code used as the example for testing HTTP interfaces in Midway Hooks. ```typescript import { Api, Get } from '@midwayjs/hooks'; export default Api(Get('/hello'), async () => { return 'Hello World!'; }); ``` -------------------------------- ### Install MikroORM component via npm Source: https://www.midwayjs.org/docs/3.0.0/extensions/mikro Install the Midway Mikro component and the MikroORM core package using npm. ```bash $ npm i @midwayjs/mikro@3 @mikro-orm/core --save ``` -------------------------------- ### Package.json scripts for mwtsc Source: https://www.midwayjs.org/docs/3.0.0/tool/mwtsc Example package.json scripts for Midway projects. The dev script uses mwtsc with --run @midwayjs/mock/app to start the framework locally; the build script uses tsc. ```json { "scripts": { "dev": "cross-env NODE_ENV=local mwtsc --watch --run @midwayjs/mock/app", "build": "cross-env rm -rf dist && tsc" }, } ``` -------------------------------- ### Get data source via MikroDataSourceManager Source: https://www.midwayjs.org/docs/3.0.0/extensions/mikro Use this to obtain the MikroORM data source instance by injecting the built-in MikroDataSourceManager and calling getDataSource('default'). The example shows retrieving the connection via orm.em.getConnection(). ```typescript import { Configuration } from '@midwayjs/core'; import { MikroDataSourceManager } from '@midwayjs/mikro'; @Configuration({ // ... }) export class MainConfiguration { async onReady(container: IMidwayContainer) { const dataSourceManager = await container.getAsync(MikroDataSourceManager); const orm = dataSourceManager.getDataSource('default'); const connection = orm.em.getConnection(); // ... } } ``` -------------------------------- ### 构建脚本示例(build.sh) Source: https://www.midwayjs.org/docs/3.0.0/deployment 示例构建脚本,可保存为 build.sh 执行。包含服务器构建和本地构建两种场景,推荐在干净环境中构建。 ```bash ## 服务器构建(已经下载好代码) $ npm install # 安装开发期依赖 $ npm run build # 构建项目 $ npm prune --production # 移除开发依赖 ## 本地构建(已经安装好 dev 依赖) $ npm run build $ npm prune --production # 移除开发依赖 ``` -------------------------------- ### Get Authentication Info from Cookie in onWebSocketUpgrade Source: https://www.midwayjs.org/docs/3.0.0/extensions/ws Shows how to retrieve authentication information from cookies within the onWebSocketUpgrade handler. The example parses the cookie header to extract a session ID and returns false if the cookie is missing. ```typescript this.wsFramework.onWebSocketUpgrade(async (request, socket, head) => { const cookie = request.headers.cookie; if (!cookie) { return false; } // 解析 cookie 获取 session 信息 const sessionId = this.parseCookie(cookie).sessionId; return await this.validateSession(sessionId); }); ``` -------------------------------- ### Get Authentication Info from URL Parameters in onWebSocketUpgrade Source: https://www.midwayjs.org/docs/3.0.0/extensions/ws Shows how to retrieve authentication information from URL query parameters within the onWebSocketUpgrade handler. The example extracts token and userId parameters and passes them to a validation method. ```typescript this.wsFramework.onWebSocketUpgrade(async (request, socket, head) => { const url = new URL(request.url, `http://${request.headers.host}`); const token = url.searchParams.get('token'); const userId = url.searchParams.get('userId'); // 验证逻辑 return await this.validateToken(token, userId); }); ``` -------------------------------- ### Use default etcd client in a service Source: https://www.midwayjs.org/docs/3.0.0/extensions/etcd Example of using the default etcd client via ETCDService. It demonstrates put, get, getAll with prefix, and delete operations. The service is provided with @Provide and injects ETCDService. ```typescript import { Provide } from '@midwayjs/core'; import { ETCDService } from '@midwayjs/etcd'; import { join } from 'path'; @Provide() export class UserService { @Inject() etcdService: ETCDService; async invoke() { await this.etcdService.put('foo').value('bar'); const fooValue = await this.etcdService.get('foo').string(); console.log('foo was:', fooValue); const allFValues = await this.etcdService.getAll().prefix('f').keys(); console.log('all our keys starting with "f":', allFValues); await this.etcdService.delete().all(); } } ``` -------------------------------- ### onConfigLoad example Source: https://www.midwayjs.org/docs/3.0.0/lifecycle Implements onConfigLoad to modify configuration during startup. The returned object is automatically merged into the configuration, so @Config can access the added properties. ```typescript // src/configuration.ts import { Configuration, ILifeCycle, IMidwayContainer } from '@midwayjs/core'; @Configuration() export class MainConfiguration implements ILifeCycle { async onConfigLoad(): Promise { // 直接返回数据,会自动合并到配置中 return { test: 1 } } } ``` -------------------------------- ### docker ps output showing Consul port mapping Source: https://www.midwayjs.org/docs/3.0.0/extensions/consul Example output of `docker ps` after starting the Consul container. The port mapped to 8500 (here 32779) is the one to use in `config.default.ts` and to open the UI at http://127.0.0.1:32779/ui/. ```bash ➜ my_consul_app docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 1b2d5b8771cb consul "docker-entrypoint.s…" 4 seconds ago Up 2 seconds 0.0.0.0:32782->8300/tcp, 0.0.0.0:32776->8301/udp, 0.0.0.0:32781->8301/tcp, 0.0.0.0:32775->8302/udp, 0.0.0.0:32780->8302/tcp, 0.0.0.0:32779->8500/tcp, 0.0.0.0:32774->8600/udp, 0.0.0.0:32778->8600/tcp cocky_wing ``` -------------------------------- ### HTTP Trigger with @ServerlessTrigger(ServerlessTriggerType.HTTP) Source: https://www.midwayjs.org/docs/3.0.0/serverless/aliyun_faas Binds an HTTP trigger to a function. Unlike API Gateway, this trigger is simpler to use and configure. The example handles GET requests at path '/' and returns a greeting with the provided name parameter. ```typescript import { Provide, Inject, ServerlessTrigger, ServerlessTriggerType } from '@midwayjs/core'; import { Context } from '@midwayjs/faas'; @Provide() export class HelloAliyunService { @Inject() ctx: Context; @ServerlessTrigger(ServerlessTriggerType.HTTP, { path: '/', method: 'get', }) async handleHTTPEvent(@Query() name = 'midway') { return `hello ${name}`; } } ``` -------------------------------- ### Bootstrap Startup with configure() Source: https://www.midwayjs.org/docs/3.0.0/deployment Use this to configure the MidwayJS Bootstrap with startup parameters, such as imports, before running the application. The configure method accepts an object with options like appDir, baseDir, imports, moduleDetector, logger, ignore, and globalConfig. ```javascript const { Bootstrap } = require('@midwayjs/bootstrap'); Bootstrap .configure({ imports: [/*...*/] }) .run(); ``` -------------------------------- ### Get Authentication Info from Request Header in onWebSocketUpgrade Source: https://www.midwayjs.org/docs/3.0.0/extensions/ws Shows how to retrieve authentication information from the Authorization request header within the onWebSocketUpgrade handler. The example extracts the token by removing the 'Bearer ' prefix and returns false if the header is missing. ```typescript this.wsFramework.onWebSocketUpgrade(async (request, socket, head) => { const authorization = request.headers.authorization; if (!authorization) { return false; } const token = authorization.replace('Bearer ', ''); return await this.validateToken(token); }); ``` -------------------------------- ### 编译并发布组件 Source: https://www.midwayjs.org/docs/3.0.0/component_development 使用 npm run build && npm publish 编译并发布组件到 npm。 ```bash ## 编译并发布对应的component $ npm run build && npm publish ``` -------------------------------- ### Package.json scripts for Serverless Source: https://www.midwayjs.org/docs/3.0.0/tool/mwtsc Package.json scripts for Serverless environments, using @midwayjs/mock/function as the startup file. ```json { "scripts": { "dev": "cross-env NODE_ENV=local mwtsc --watch --run @midwayjs/mock/function", }, } ```