### PM2 for Backend Service Management Source: https://node.cool-admin.com/src/guide/deploy Demonstrates how to install and use PM2, a process manager for Node.js applications. It covers starting, listing, stopping, restarting, deleting services, and viewing logs. Includes an example of starting a service in cluster mode for scalability. ```shell // Command-line installation of pm2 npm install pm2 -g // Common commands // Start a service pm2 start // List current services pm2 list // Stop a service pm2 stop // Restart a service pm2 restart // Delete a service pm2 delete // View service output logs pm2 logs // Cluster mode startup // -i specifies the number of instances // max means PM2 will automatically detect the number of available CPUs, or you can specify a number pm2 start ./bootstrap.js -i max --name cool-admin(change to your application name) // Restart pm2 restart cool-admin // Logs pm2 logs cool-admin // Default log location /root/.pm2/logs ``` -------------------------------- ### Install and Configure pnpm Source: https://node.cool-admin.com/src/guide/deploy Installs pnpm globally and configures it to use the Taobao mirror registry for faster package downloads. pnpm is recommended for managing project dependencies. ```bash npm install -g pnpm pnpm config set registry https://registry.npmmirror.com ``` -------------------------------- ### Install Project Dependencies (npm) Source: https://node.cool-admin.com/src/guide/quick Command to install project dependencies using npm. ```shell npm install ``` -------------------------------- ### Install Project Dependencies (yarn) Source: https://node.cool-admin.com/src/guide/quick Command to install project dependencies using yarn. ```shell yarn ``` -------------------------------- ### Install and Run Frontend Dependencies (pnpm, npm, yarn) Source: https://node.cool-admin.com/src/guide/quick Instructions for installing project dependencies and running the development server using pnpm, npm, or yarn. This is typically executed at the project root. ```shell # Install dependencies pnpm i # Run pnpm dev ``` ```shell # Install dependencies npm install # Run npm run dev ``` ```shell # Install dependencies yarn # Run yarn dev ``` -------------------------------- ### Install File Plugin Source: https://node.cool-admin.com/src/guide/core/file Instructions for installing the `@cool-midway/file` plugin using yarn or npm. ```APIDOC ## Install Plugin ### Description Install the `@cool-midway/file` plugin which includes various upload methods. ### Using Yarn ```bash yarn add @cool-midway/file ``` ### Using npm ```bash npm install @cool-midway/file --save ``` ### Configuration `src/configuration.ts` ```typescript import { Configuration, App } from "@midwayjs/core"; import { join } from "path"; import * as file from "@cool-midway/file"; @Configuration({ imports: [file], importConfigs: [join(__dirname, "./config")], }) export class ContainerLifeCycle { @App() app: koa.Application; async onReady() {} } ``` ``` -------------------------------- ### Executing the Service Control Script Source: https://node.cool-admin.com/src/guide/deploy These commands demonstrate how to run the 'serve.sh' script to start, stop, or restart the Node Cool Admin service. The script takes 'start', 'stop', or 'restart' as command-line arguments. ```bash // 启动 ./serve.sh start // 停止 ./serve.sh stop // 重启 ./serve.sh restart ``` -------------------------------- ### Native Application Startup Script (Linux) Source: https://node.cool-admin.com/src/guide/deploy A bash script for starting, stopping, and restarting a native Cool Admin application on Linux. It manages the process using a PID file and logs output to a file. ```bash #!/bin/bash # Application name (for display and process lookup) APP_NAME="cool-admin" # Actual application executable path (replace with your actual path) APP_EXEC="./cool-admin-linux" # Path to save the PID file PID_FILE="./serve.pid" # Log output file LOG_FILE="./app.log" ### Function definitions ### start() { if [ -f "$PID_FILE" ]; then echo "Error: $APP_NAME is already running (PID: $(cat $PID_FILE))" exit 1 fi echo "Starting $APP_NAME ..." nohup $APP_EXEC > $LOG_FILE 2>&1 & echo $! > $PID_FILE echo "✓ Successfully started $APP_NAME (PID: $!)" } stop() { if [ ! -f "$PID_FILE" ]; then echo "Error: $APP_NAME is not running" exit 1 fi PID=$(cat $PID_FILE) echo "Stopping $APP_NAME (PID: $PID) ..." kill $PID && rm -f $PID_FILE echo "✓ Stopped $APP_NAME" } restart() { echo "Restarting $APP_NAME..." stop sleep 1 # Wait for the process to fully release start } ``` -------------------------------- ### Running the Frontend Source: https://node.cool-admin.com/src/guide/quick Instructions on how to install dependencies and run the frontend application using pnpm, npm, or yarn. ```APIDOC ## Running the Frontend To run the frontend application, navigate to the project root directory (the same level as `package.json`) and execute the following commands based on your package manager. ### Using pnpm ```sh # Install dependencies pnpm i # Run the application pnpm dev ``` ### Using npm ```sh # Install dependencies npm install # Run the application npm run dev ``` ### Using yarn ```sh # Install dependencies yarn # Run the application yarn dev ``` After running, the application will be accessible at `http://127.0.0.1:9000/`. The default credentials are: - **Account:** admin - **Password:** 123456 ``` -------------------------------- ### Install Project Dependencies (pnpm) Source: https://node.cool-admin.com/src/guide/quick Command to install project dependencies using pnpm. ```shell pnpm i ``` -------------------------------- ### Run Development Server (npm) Source: https://node.cool-admin.com/src/guide/quick Command to start the Cool Admin development server using npm. ```shell npm run dev ``` -------------------------------- ### Install PostgreSQL Driver for TypeORM Source: https://node.cool-admin.com/src/guide/core/db Before configuring PostgreSQL with TypeORM in Cool Admin, you need to install the `pg` package. This command uses npm to add the PostgreSQL driver as a dependency to your project. ```shell npm install pg --save ``` -------------------------------- ### MySQL Database Configuration (TypeScript) Source: https://node.cool-admin.com/src/guide/core/pkg Example of configuring a MySQL database connection within the application. It includes entity paths and subscriber configurations. Avoid using broad entity paths like '**/modules/*/entity' in production if it causes issues. ```typescript import { entities } from '../entities'; { type: 'mysql', entities, // 订阅者 subscribers: [TenantSubscriber], } ``` -------------------------------- ### Run Development Server (pnpm) Source: https://node.cool-admin.com/src/guide/quick Command to start the Cool Admin development server using pnpm. ```shell pnpm dev ``` -------------------------------- ### Build Backend for Native Packaging (Bash) Source: https://node.cool-admin.com/src/guide/core/pkg This command initiates the backend packaging process using npm. It's recommended to use npm if encountering issues with pnpm. The output will be in the 'build' directory. ```bash // 如果使用pnpm命令遇到问题,建议使用npm命令 npm run pkg ``` -------------------------------- ### Run Development Server (yarn) Source: https://node.cool-admin.com/src/guide/quick Command to start the Cool Admin development server using yarn. ```shell yarn dev ``` -------------------------------- ### Nginx Configuration for Cool Admin Source: https://node.cool-admin.com/src/guide/deploy Provides an example Nginx configuration for proxying requests to the Cool Admin backend and serving static frontend files. It includes settings for handling API requests, caching, persistent connections, and WebSocket connections. ```nginx upstream cool { server 127.0.0.1:8001; } server { ... # Frontend build output directory root /home/test/front; # Handle 404 for frontend routing location / { try_files $uri $uri/ /index.html; } # Proxy backend API requests location /api/ { proxy_pass http://cool/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header REMOTE-HOST $remote_addr; proxy_cache_bypass no_cache; # Caching configuration (commented out) #proxy_cache cache_one; #proxy_cache_key $host$request_uri$is_args$args; #proxy_cache_valid 200 304 301 302 1h; # Persistent connection configuration (commented out) #proxy_connect_timeout 3000s; #proxy_read_timeout 86400s; #proxy_send_timeout 3000s; #proxy_http_version 1.1; #proxy_set_header Upgrade $http_upgrade; #proxy_set_header Connection "upgrade"; add_header X-Cache $upstream_cache_status; # SSE specific configuration for streaming responses proxy_buffering off; proxy_cache off; proxy_http_version 1.1; proxy_set_header Connection ''; chunked_transfer_encoding off; #expires 12h; } # Additional configuration for socket connections location /socket { proxy_pass http://cool/socket; proxy_connect_timeout 3600s; # Configuration point 1 proxy_read_timeout 3600s; # Configuration point 2, if ineffective, consider increasing this timeout proxy_send_timeout 3600s; # Configuration point 3 proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header REMOTE-HOST $remote_addr; #proxy_bind $remote_addr transparent; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; rewrite /socket/(.*) /$1 break; proxy_redirect off; } } ``` -------------------------------- ### Build Frontend for Native Packaging (Bash) Source: https://node.cool-admin.com/src/guide/core/pkg This command builds the static frontend assets required for native packaging. After execution, the 'dist' directory should be copied to the backend's 'public' directory. ```bash # 在前端项目目录下执行 npm run build-static ``` -------------------------------- ### Install Cool Admin File Plugin (Bash) Source: https://node.cool-admin.com/src/guide/core/file Commands to install the `@cool-midway/file` plugin using either Yarn or npm package managers. This plugin provides file upload capabilities. ```bash yarn add @cool-midway/file ``` ```bash npm install @cool-midway/file --save ``` -------------------------------- ### Install Alipay Plugin for Cool Admin Source: https://node.cool-admin.com/src/guide/core/pay This command installs the necessary Alipay plugin for Cool Admin. This is a prerequisite for integrating Alipay payment functionality. ```shell @cool-midway/pay ``` -------------------------------- ### Docker Image Building and Running Source: https://node.cool-admin.com/src/guide/deploy Commands for building Docker images for the Cool Admin backend and frontend, and for running these containers. It includes creating a Docker network and mapping ports. ```shell // Create docker network docker network create cool // Build backend image docker build -t cool-admin-midway:1.0 . // Build frontend image docker build -t cool-admin-vue:1.0 . // Run backend docker run --network cool -p 8001:8001 --name midway cool-admin-midway:1.0 // Run frontend docker run --network cool -p 80:80 --name vue cool-admin-vue:1.0 ``` -------------------------------- ### Native Packaging Configuration (JSON) Source: https://node.cool-admin.com/src/guide/core/pkg Configuration for the 'pkg' tool, specifying files to include, assets, target platforms, and the output directory for the native package. ```json { "pkg": { "scripts": [ "dist/**/*", "node_modules/axios/dist/node/*" ], "assets": [ "public/**/*", "typings/**/*" ], "targets": [ "node20-macos-x64" ], "outputPath": "build" } } ``` -------------------------------- ### Install SQLite Driver for TypeORM Source: https://node.cool-admin.com/src/guide/core/db To use SQLite with TypeORM in Cool Admin, you must first install the `sqlite3` package. This command adds the necessary driver to your project dependencies using npm. ```shell npm install sqlite3 --save ``` -------------------------------- ### Replace Midway Decorator Dependency in TypeScript Source: https://node.cool-admin.com/src/todo/upgrade This code snippet demonstrates how to replace the '@midwayjs/decorator' import with '@midwayjs/core' in a TypeScript project, a common step during the Cool Admin v7.x to v8.x upgrade. Ensure you have the necessary dependencies installed. ```typescript import { BaseEntity } from "../../base/entity/base"; ``` -------------------------------- ### Shell Script Logic for Service Control Source: https://node.cool-admin.com/src/guide/deploy This bash script defines the main logic for controlling the Node Cool Admin service. It accepts 'start', 'stop', or 'restart' as arguments to manage the service. It also provides a usage message for invalid arguments. ```bash case "$1" in start) start ;; stop) stop ;; restart) restart ;; *) echo "使用方法: $0 {start|stop|restart}" exit 1 esac exit 0 ``` -------------------------------- ### Configure npm Registry to Alibaba Mirror Source: https://node.cool-admin.com/src/guide/quick Commands to configure npm, pnpm, or yarn to use the Alibaba mirror registry for faster dependency downloads. ```shell # pnpm pnpm config set registry https://registry.npmmirror.com/ # npm npm config set registry https://registry.npmmirror.com/ # yarn yarn config set registry https://registry.npmmirror.com/ ``` -------------------------------- ### Manual Route Prefixing with Generic CRUD Setup Source: https://node.cool-admin.com/src/guide/core/controller Shows how to manually set a route prefix and enable generic CRUD operations (add, delete, update, info, list, page) for a controller. This requires specifying the entity class. ```typescript import { Get } from "@midwayjs/core"; import { CoolController, BaseController } from "@cool-midway/core"; import { DemoGoodsEntity } from "../../entity/goods"; /** * 商品 */ @CoolController({ prefix: "/api", api: ["add", "delete", "update", "info", "list", "page"], entity: DemoGoodsEntity, }) export class AppDemoGoodsController extends BaseController { /** * 其他接口 */ @Get("/other") async other() { return this.ok("hello, cool-admin!!!"); } } ``` -------------------------------- ### Install WeChat Pay Plugin for Cool Admin Source: https://node.cool-admin.com/src/guide/core/pay This command installs the necessary WeChat Pay plugin for Cool Admin using npm. Ensure you have Node.js and npm installed. ```shell npm install @cool-midway/pay ``` -------------------------------- ### TypeORM Basic Operations in TypeScript Service Source: https://node.cool-admin.com/src/guide/core/service This TypeScript example illustrates common data manipulation operations using TypeORM within a custom Service class. It covers inserting single and multiple records, saving entities, finding single and multiple records by ID or conditions, deleting records, and updating records by ID or criteria. This snippet serves as a practical guide for interacting with the database using TypeORM's repository pattern. ```typescript import { DemoGoodsEntity } from "./../entity/goods"; import { Provide } from "@midwayjs/core"; import { BaseService } from "@cool-midway/core"; import { InjectEntityModel } from "@midwayjs/typeorm"; import { In, Repository } from "typeorm"; /** * 商品示例 */ @Provide() export class DemoGoodsService extends BaseService { @InjectEntityModel(DemoGoodsEntity) demoGoodsEntity: Repository; async typeorm() { // 新增单个,传入的参数字段在数据库中一定要存在 await this.demoGoodsEntity.insert({ title: "xxx" }); // 新增单个,传入的参数字段在数据库中可以不存在 await this.demoGoodsEntity.save({ title: "xxx" }); // 新增多个 await this.demoGoodsEntity.save([{ title: "xxx" }]); // 查找单个 await this.demoGoodsEntity.findOneBy({ id: 1 }); // 查找多个 await this.demoGoodsEntity.findBy({ id: In([1, 2]) }); // 删除单个 await this.demoGoodsEntity.delete(1); // 删除多个 await this.demoGoodsEntity.delete([1]); // 根据ID更新 await this.demoGoodsEntity.update(1, { title: "xxx" }); // 根据条件更新 await this.demoGoodsEntity.update({ price: 20 }, { title: "xxx" }); // 多条件操作 await this.demoGoodsEntity .createQueryBuilder() .where("id = :id", { id: 1 }) .andWhere("price = :price", { price: 20 }) .getOne(); } } ``` -------------------------------- ### JSON Data Import Example (`db.json`) Source: https://node.cool-admin.com/src/guide/core/module Shows how to define initial data for a module using a `db.json` file. It supports importing data into tables like `dict_type` and `dict_info`, including hierarchical data relationships using the `@childDatas` and `@id` special fields. ```json { "dict_type": [ { "name": "升级类型", "key": "upgradeType" } ] } ``` ```json { "dict_type": [ { "name": "升级类型", "key": "upgradeType", "@childDatas": { "dict_info": [ { "typeId": "@id", "name": "安卓", "orderNum": 1, "remark": null, "parentId": null, "value": "0" }, { "typeId": "@id", "name": "IOS", "orderNum": 1, "remark": null, "parentId": null, "value": "1" } ] } } ] } ``` -------------------------------- ### Install Redis Cache Dependency (Older Versions) Source: https://node.cool-admin.com/src/guide/core/cache For older versions of Cool Admin, you can install the `cache-manager-ioredis` package using pnpm to enable Redis caching. ```bash pnpm i cache-manager-ioredis --save ``` -------------------------------- ### Install Redis Cache Dependency (v7.1+) Source: https://node.cool-admin.com/src/guide/core/cache To use Redis caching in Cool Admin version 7.1 and above, you need to install the `cache-manager-ioredis-yet` package using pnpm. ```bash pnpm i cache-manager-ioredis-yet --save ``` -------------------------------- ### Install Elasticsearch Module for Cool Admin Source: https://node.cool-admin.com/src/guide/core/es Installs the necessary Elasticsearch module for Cool Admin using pnpm. This is the first step to enable Elasticsearch functionality in your project. ```shell pnpm add @cool-midway/es ``` -------------------------------- ### Menu Import Example (`menu.json`) Source: https://node.cool-admin.com/src/guide/core/module Defines the menu structure for a module using a `menu.json` file. This JSON array allows for the creation of nested menus with properties like name, router path, icon, order, and child menus, facilitating the integration of module features into the admin UI. ```json [ { "name": "应用管理", "router": null, "perms": null, "type": 0, "icon": "icon-app", "orderNum": 2, "viewPath": null, "keepAlive": true, "isShow": true, "childMenus": [ { "name": "套餐管理", "router": "/app/goods", "perms": null, "type": 1, "icon": "icon-goods", "orderNum": 0, "viewPath": "modules/app/views/goods.vue", "keepAlive": true, "isShow": true } ] } ] ``` -------------------------------- ### Project Structure Overview Source: https://node.cool-admin.com/src/guide/quick Overview of the main directory structure for the Cool Admin project, highlighting key directories like .vscode, public, src, and test. ```tree ├── .vscode(代码片段,根据关键字可以快速地生成代码) ├── public(静态资源文件,如js、css或者上传的文件) ├── src │ └── comm(通用库) │ └── modules(项目模块) │ └── config │ │ └── config.default.ts(默认配置,不区分环境,都生效) │ │ └── config.local.ts(本地开发配置,对应npm run dev) │ │ └── config.prod.ts(生产环境配置,对应npm run start) │ │ └── plugin.ts(插件配置) │ └── configuration.ts(midway的配置文件) │ └── welcome.ts(环境的controller) │ └── interface.ts(类型声明) ├── test ├── package.json(依赖管理,项目信息) ├── bootstrap.js(生产环境启动入口文件,可借助pm2等工具多进程启动) └── tsconfig.json ``` -------------------------------- ### Implement Cache Set and Get Operations Source: https://node.cool-admin.com/src/guide/core/cache This TypeScript controller demonstrates how to use the `MidwayCache` service to set and get cache values. It shows setting a cache with and without an expiration time, and retrieving a cached value. ```typescript import { DemoCacheService } from "../../service/cache"; import { Inject, Post, Provide, Get, InjectClient } from "@midwayjs/core"; import { CoolController, BaseController } from "@cool-midway/core"; import { CachingFactory, MidwayCache } from "@midwayjs/cache-manager"; /** * 缓存 */ @Provide() @CoolController() export class AppDemoCacheController extends BaseController { @InjectClient(CachingFactory, "default") midwayCache: MidwayCache; @Inject() demoCacheService: DemoCacheService; /** * 设置缓存 * @returns */ @Post("/set") async set() { await this.midwayCache.set("a", 1); // 缓存10秒 await this.midwayCache.set("a", 1, 10 * 1000); return this.ok(await this.midwayCache.get("a")); } /** * 获得缓存 * @returns */ @Get("/get") async get() { return this.ok(await this.demoCacheService.get()); } } ``` -------------------------------- ### Manual Route Prefixing with Basic Controller Source: https://node.cool-admin.com/src/guide/core/controller Demonstrates setting a manual route prefix for a controller. This approach is not recommended if global permission validation is in use, as it might cause issues. It includes a basic 'other' endpoint. ```typescript import { CoolController, BaseController } from "@cool-midway/core"; /** * 商品 */ @CoolController("/api") export class AppDemoGoodsController extends BaseController { /** * 其他接口 */ @Get("/other") async other() { return this.ok("hello, cool-admin!!!"); } } ``` -------------------------------- ### Other Endpoint Source: https://node.cool-admin.com/src/guide/core/controller A simple GET endpoint that returns a greeting message. ```APIDOC ## GET /other ### Description Returns a simple greeting message. ### Method GET ### Endpoint /other ### Success Response (200) - **message** (string) - A greeting message. ### Response Example ```json { "message": "hello, cool-admin!!!" } ``` ``` -------------------------------- ### 获取插件实例和配置 - TypeScript Source: https://node.cool-admin.com/src/guide/plugin 展示了如何在 TypeScript 代码中获取插件实例和配置。通过 `pluginService.getInstance` 获取插件实例,然后调用其实例方法;通过 `pluginService.getConfig` 获取插件配置。 ```typescript @Inject() pluginService: PluginService; // 获得插件的实例 const instance = await this.pluginService.getInstance("插件标识key"); const result = await instance['demo'](); // 获得插件的配置 const config = await this.pluginService.getConfig("插件标识key"); ``` -------------------------------- ### Implement Database Transaction with CoolTransaction Decorator Source: https://node.cool-admin.com/src/guide/core/db This TypeScript example demonstrates how to use the `@CoolTransaction` decorator provided by Cool Admin to manage database transactions. The decorator handles transaction initiation and rollback on exceptions. Database operations within the decorated method must use the injected `queryRunner` to be part of the transaction. ```typescript import { Inject, Provide } from "@midwayjs/core"; import { BaseService, CoolTransaction } from "@cool-midway/core"; import { InjectEntityModel } from "@@midwayjs/typeorm"; import { Repository, QueryRunner } from "typeorm"; import { DemoAppGoodsEntity } from "../entity/goods"; /** * 商品 */ @Provide() export class DemoGoodsService extends BaseService { @InjectEntityModel(DemoAppGoodsEntity) demoAppGoodsEntity: Repository; /** * 事务 * @param params * @param queryRunner 无需调用者传参, 自动注入,最后一个参数 */ @CoolTransaction({ isolation: "SERIALIZABLE" }) async testTransaction(params: any, queryRunner?: QueryRunner) { await queryRunner.manager.insert(DemoAppGoodsEntity, { title: "这是个商品", pic: "商品图", price: 99.0, type: 1, }); } } // TIP // `CoolTransaction`中已经做了异常捕获,所以方法内部无需捕获异常,必须使用`queryRunner`做数据库操作, 而且不能是异步的,否则事务无效, `queryRunner`会注入到被注解的方法最后一个参数中, 无需调用者传参 ``` -------------------------------- ### Automatic Route Prefixing with Generic CRUD Setup Source: https://node.cool-admin.com/src/guide/core/controller Illustrates automatic route prefix generation based on file structure, combined with generic CRUD operations. The route prefix is derived from the module and controller file path, and the entity is specified. ```typescript import { Get } from "@midwayjs/core"; import { CoolController, BaseController } from "@cool-midway/core"; import { DemoGoodsEntity } from "../../entity/goods"; /** * 商品 */ @CoolController({ api: ["add", "delete", "update", "info", "list", "page"], entity: DemoGoodsEntity, }) export class AppDemoGoodsController extends BaseController { /** * 其他接口 */ @Get("/other") async other() { return this.ok("hello, cool-admin!!!"); } } ``` -------------------------------- ### Configure Goods Controller with CRUD and Custom Query Options (TypeScript) Source: https://node.cool-admin.com/src/guide/core/controller This TypeScript code configures a `DemoAppGoodsController` for managing goods. It enables standard CRUD operations ('add', 'delete', 'update', 'info', 'list', 'page') and customizes the 'page' query with various options like keyword searching, field equality checks, joins with the `BaseSysUserEntity`, and dynamic `where` clauses. It also includes logic for inserting the user ID and transforming request data before saving. ```typescript import { Get } from "@midwayjs/core"; import { CoolController, BaseController } from "@cool-midway/core"; import { BaseSysUserEntity } from "../../../base/entity/sys/user"; import { DemoAppGoodsEntity } from "../../entity/goods"; /** * 商品 */ @CoolController({ // 添加通用CRUD接口 api: ["add", "delete", "update", "info", "list", "page"], // 8.x新增,将service方法注册为api,通过post请求,直接调用service方法 serviceApis: [ 'use', { method: 'test1', summary: '不使用多租户', // 接口描述 }, 'test2', // 也可以不设置summary ] // 设置表实体 entity: DemoAppGoodsEntity, // 向表插入当前登录用户ID insertParam: (ctx) => { return { // 获得当前登录的后台用户ID,需要请求头传Authorization参数 userId: ctx.admin.userId, }; }, // 操作crud之前做的事情 @cool-midway/core@3.2.14 新增 before: (ctx) => { // 将前端的数据转JSON格式存数据库 const { data } = ctx.request.body; ctx.request.body.data = JSON.stringify(data); }, // info接口忽略价格字段 infoIgnoreProperty: ["price"], // 分页查询配置 pageQueryOp: { // 让title字段支持模糊查询,请求参数为keyWord keyWordLikeFields: ["title"], // 让type字段支持筛选,请求筛选字段与表字段一致是情况 fieldEq: ["type"], // 多表关联,请求筛选字段与表字段不一致的情况 fieldEq: [{ column: "a.id", requestParam: "id" }], // 让title字段支持模糊查询,请求参数为title fieldLike: ['a.title'], // 让title字段支持模糊查询,请求筛选字段与表字段不一致的情况 fieldLike: [{ column: "a.title", requestParam: "title" }], // 指定返回字段,注意多表查询这个是必要的,否则会出现重复字段的问题 select: ["a.*", "b.name", "a.name AS userName"], // 4.x置为过时 改用 join 关联表用户表 leftJoin: [ { entity: BaseSysUserEntity, alias: "b", condition: "a.userId = b.id", }, ], // 4.x新增 join: [ { entity: BaseSysUserEntity, alias: "b", condition: "a.userId = b.id", type: "innerJoin", }, ], // 4.x 新增 追加其他条件 extend: async (find: SelectQueryBuilder) => { find.groupBy("a.id"); }, // 增加其他条件 where: async (ctx) => { // 获取body参数 const { a } = ctx.request.body; return [ // 价格大于90 ["a.price > :price", { price: 90.0 }], // 满足条件才会执行 ["a.price > :price", { price: 90.0 }, "条件"], // 多个条件一起 [ "(a.price = :price or a.userId = :userId)", { price: 90.0, userId: ctx.admin.userId }, ], ]; }, // 添加排序 addOrderBy: { price: "desc", }, }, }) export class DemoAppGoodsController extends BaseController { /** * 其他接口 */ @Get("/other") async other() { return this.ok("hello, cool-admin!!!"); } } ``` -------------------------------- ### 测试插件 (`test/index.ts`) - TypeScript Source: https://node.cool-admin.com/src/guide/plugin 展示了如何编写插件的测试文件。通过实例化插件类,调用 `init` 方法传入插件信息,然后执行插件的各种方法进行测试。 ```typescript import { Plugin } from "../src/index"; import pluginInfo from "../plugin.json"; // 实例化插件 const indexInstance = new Plugin(); // 初始化插件 indexInstance.init(pluginInfo); // 调用插件方法 indexInstance.demo(); ``` -------------------------------- ### 执行插件测试和打包 - Bash Source: https://node.cool-admin.com/src/guide/plugin 提供了用于测试和打包插件的 Bash 命令。`npm run dev` 用于开发模式运行,`npm run test` 用于执行测试,`npm run release` 用于生成插件包。 ```bash // 运行测试 npm run dev // 此操作会先编译成js文件,然后执行测试 npm run test // 打包命令 npm run release ```