### Install and Run Frontend Development Server Source: https://github.com/cool-team-official/cool-admin-midway-docs/blob/main/src/guide/quick.md Commands to install dependencies and start the development server for the frontend project using different package managers. ```shell # 安装依赖 pnpm i # 运行 pnpm dev ``` ```shell # 安装依赖 npm install # 运行 npm run dev ``` ```shell # 安装依赖 yarn # 运行 yarn dev ``` -------------------------------- ### Clone and Start Cool Admin Node Project Source: https://context7.com/cool-team-official/cool-admin-midway-docs/llms.txt Instructions to clone the backend project, install dependencies, and start the development server. Access the application at http://127.0.0.1:8001 with default credentials. ```shell # 克隆后端项目 git clone https://github.com/cool-team-official/cool-admin-midway.git cd cool-admin-midway # 安装依赖 pnpm i # 启动开发服务器(自动建表、自动导入初始数据) pnpm dev # 访问 http://127.0.0.1:8001 # 默认账户: admin 密码: 123456 ``` -------------------------------- ### Database Configuration Example (MySQL) Source: https://context7.com/cool-team-official/cool-admin-midway-docs/llms.txt Example configuration for connecting to a MySQL database using TypeORM. Includes settings for host, port, credentials, and automatic table synchronization. Supports PostgreSQL and SQLite with appropriate driver installations. ```typescript // src/config/config.local.ts —— MySQL 配置示例 import { MidwayConfig } from "@midwayjs/core"; export default { typeorm: { dataSource: { default: { type: "mysql", host: "127.0.0.1", port: 3306, username: "root", password: "123456", database: "cool", synchronize: true, // 自动建表,生产环境请关闭 logging: false, charset: "utf8mb4", cache: true, entities: ["**/modules/*/entity"], }, }, }, } as MidwayConfig; // PostgreSQL:type: "postgres",需先安装驱动 npm install pg --save // SQLite:type: "sqlite",database: path.join(__dirname, "../../cool.sqlite"),需先安装 npm install sqlite3 --save ``` -------------------------------- ### Install Backend Dependencies Source: https://github.com/cool-team-official/cool-admin-midway-docs/blob/main/src/guide/quick.md Install backend project dependencies using pnpm, npm, or yarn. Choose the package manager that suits your project setup. ```shell pnpm i ``` ```shell npm install ``` ```shell yarn ``` -------------------------------- ### Plugin Configuration Example Source: https://github.com/cool-team-official/cool-admin-midway-docs/blob/main/src/guide/core/plugin.md Illustrates how to configure plugins using JSON, including environment-specific settings for local and production. ```json { "appId": "xxxxx", "appSecret": "xxxxx", "filePath": "@baseDir/xxx.txt" } ``` ```json { "@local": { "appId": "xxxxx", "appSecret": "xxxxx" }, "@prod": { "appId": "xxxxx", "appSecret": "xxxxx" } } ``` -------------------------------- ### Install PostgreSQL Driver Source: https://github.com/cool-team-official/cool-admin-midway-docs/blob/main/src/guide/core/db.md Install the PostgreSQL driver using npm. ```shell npm install pg --save ``` -------------------------------- ### Install @cool-midway/pay Plugin Source: https://github.com/cool-team-official/cool-admin-midway-docs/blob/main/src/guide/core/pay.md Install the @cool-midway/pay plugin using npm. This is the first step for integrating payment functionalities. ```shell npm install @cool-midway/pay ``` -------------------------------- ### Qiniu Cloud Example Configuration (TypeScript) Source: https://github.com/cool-team-official/cool-admin-midway-docs/blob/main/src/guide/core/file.md An example configuration for Qiniu Cloud, demonstrating how to fill in the access key ID, secret access key, bucket name, region, and public domain. ```typescript cool: { // 是否自动导入数据库 file: { // 上传模式 本地上传或云存储 mode: MODETYPE.CLOUD, qiniu: { accessKeyId: 'accessKeyId', accessKeySecret: 'accessKeySecret', bucket: 'bucket', region: 'z0', publicDomain: 'http://qiniu.cool-js.com', }, }, } as CoolConfig, ``` -------------------------------- ### SQLite Database Configuration Example Source: https://github.com/cool-team-official/cool-admin-midway-docs/blob/main/src/guide/core/pkg.md An example of configuring the database to use SQLite for local deployment. This configuration includes setting the database path, enabling synchronization, and specifying entity paths. ```typescript import { TenantSubscriber } from '../modules/tenant/subscriber'; import { pSqlitePath } from '../comm/path'; { type: 'sqlite', // Database file path database: pSqlitePath(), // Auto-create tables. Note: Do not use this in production as it may lead to data loss synchronize: true, // Log SQL queries logging: false, // Entity paths entities: ['**/modules/*/entity'], // Subscribers subscribers: [TenantSubscriber], } ``` -------------------------------- ### MySQL Database Configuration Example Source: https://github.com/cool-team-official/cool-admin-midway-docs/blob/main/src/guide/core/pkg.md This is an example of a MySQL database configuration. Note that the 'entities' configuration should not be set to '**/modules/*/entity' to avoid issues. ```typescript import { TenantSubscriber } from '../modules/tenant/subscriber'; { type: 'mysql', // entities: ['**/modules/*/entity'], // This configuration is incorrect // Correct configuration: entities: entities, // Subscribers subscribers: [TenantSubscriber], } ``` -------------------------------- ### Install pnpm Source: https://github.com/cool-team-official/cool-admin-midway-docs/blob/main/src/guide/deploy.md Install pnpm globally using npm. ```bash npm install -g pnpm ``` -------------------------------- ### Run Development Server Source: https://github.com/cool-team-official/cool-admin-midway-docs/blob/main/src/guide/quick.md Commands to start the development server for the backend project using different package managers. ```shell pnpm dev ``` ```shell npm run dev ``` ```shell yarn dev ``` -------------------------------- ### Install SQLite Driver Source: https://github.com/cool-team-official/cool-admin-midway-docs/blob/main/src/guide/core/db.md Install the SQLite driver using npm. ```shell npm install sqlite3 --save ``` -------------------------------- ### Cache Controller Example Source: https://github.com/cool-team-official/cool-admin-midway-docs/blob/main/src/guide/core/cache.md Demonstrates setting and getting cache values using the injected MidwayCache client. Cache can be set with or without an expiration time. ```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()); } } ``` -------------------------------- ### AWS S3 Example Configuration (TypeScript) Source: https://github.com/cool-team-official/cool-admin-midway-docs/blob/main/src/guide/core/file.md An example configuration for AWS S3, demonstrating how to fill in the access key ID, secret access key, bucket name, and region. ```typescript cool: { // 是否自动导入数据库 file: { // 上传模式 本地上传或云存储 mode: MODETYPE.CLOUD, aws: { accessKeyId: 'accessKeyId', secretAccessKey: 'accessKeySecret', bucket: 'bucket', region: 'ap-northeast-1', }, }, } as CoolConfig, ``` -------------------------------- ### Start Service with PM2 Source: https://github.com/cool-team-official/cool-admin-midway-docs/blob/main/src/guide/deploy.md Start a service using PM2 with a specified number of instances and application name. ```shell pm2 start ./bootstrap.js -i max --name cool-admin(改成自己的应用名称) ``` -------------------------------- ### Install PM2 Source: https://github.com/cool-team-official/cool-admin-midway-docs/blob/main/src/guide/deploy.md Install PM2, a process manager for Node.js applications, globally. ```shell npm install pm2 -g ``` -------------------------------- ### Get Plugin Instance and Configuration Source: https://github.com/cool-team-official/cool-admin-midway-docs/blob/main/src/guide/core/plugin.md Shows how to obtain a plugin instance using `getInstance` and retrieve its configuration using `getConfig`. ```typescript @Inject() pluginService: PluginService; // 获得插件的实例 const instance = await this.pluginService.getInstance("插件标识key"); const result = await instance['demo'](); // 获得插件的配置 const config = await this.pluginService.getConfig("插件标识key"); ``` -------------------------------- ### Install Alipay Plugin Source: https://github.com/cool-team-official/cool-admin-midway-docs/blob/main/src/guide/core/pay.md The Alipay plugin is part of the `@cool-midway/pay` package. Ensure this package is installed. ```shell @cool-midway/pay ``` -------------------------------- ### Clone Microservice Template Project Source: https://github.com/cool-team-official/cool-admin-midway-docs/blob/main/src/guide/core/rpc.md Use this command to clone the Cool-Admin microservice template project to get started. ```shell git clone https://github.com/cool-team-official/cool-admin-midway-rpc.git ``` -------------------------------- ### Install Elasticsearch Package Source: https://github.com/cool-team-official/cool-admin-midway-docs/blob/main/src/guide/core/es.md Install the necessary Elasticsearch package for Cool-Admin using pnpm. ```shell pnpm add @cool-midway/es ``` -------------------------------- ### Install @cool-midway/file Plugin Source: https://github.com/cool-team-official/cool-admin-midway-docs/blob/main/src/guide/core/file.md Install the @cool-midway/file plugin using Yarn or NPM. This plugin includes support for various upload methods. ```bash yarn add @cool-midway/file ``` ```bash npm install @cool-midway/file --save ``` -------------------------------- ### Switch to AliMirror Registry Source: https://github.com/cool-team-official/cool-admin-midway-docs/blob/main/src/guide/quick.md Switch your package manager registry to AliMirror if you encounter network issues during dependency installation. This can speed up downloads. ```shell # pnpm pnpm config set registry https://registry.npmmirror.com/ ``` -------------------------------- ### Local Task Cron Rule Examples Source: https://github.com/cool-team-official/cool-admin-midway-docs/blob/main/src/guide/core/task.md Examples of cron expressions for scheduling local tasks, including intervals for seconds, minutes, hours, days, and weeks. ```text - 每 5 秒执行一次: `*/5 * * * * *` - 每 5 分钟执行一次: `*/5 * * * *` - 每小时执行一次: `0 * * * *` - 每天执行一次: `0 0 * * *` - 每天 1 点执行: `0 1 * * *` - 每周执行一次: `0 0 * * 0` - 每月执行一次: `0 0 1 * *` ``` -------------------------------- ### Install Redis Cache Dependency (v7.1+) Source: https://github.com/cool-team-official/cool-admin-midway-docs/blob/main/src/guide/core/cache.md Install the necessary package for Redis caching in v7.1 and later versions. Refer to MidwayJS cache documentation for more details. ```bash pnpm i cache-manager-ioredis-yet --save ``` -------------------------------- ### Invoke and Develop Plugins Source: https://context7.com/cool-team-official/cool-admin-midway-docs/llms.txt Demonstrates how to invoke installed plugins using `pluginService.invoke` and retrieve plugin configurations with `pluginService.getConfig`. It also shows how to develop a custom plugin by extending `BasePlugin`, implementing methods like `ready`, `chat`, and utilizing caching. ```typescript // 1、调用已安装的插件 import { Inject, Get, Provide } from "@midwayjs/core"; import { CoolController, BaseController } from "@cool-midway/core"; import { PluginService } from "../../../plugin/service/info"; @Provide() @CoolController() export class OpenDemoPluginController extends BaseController { @Inject() pluginService: PluginService; @Get("/invoke") async invoke() { // invoke(插件key, 方法名, ...参数) const result = await this.pluginService.invoke("zhipu-ai", "chat", "你好"); return this.ok(result); } @Get("/config") async config() { // 获取插件配置(在后台 UI 中配置,不写在代码里) const config = await this.pluginService.getConfig("zhipu-ai"); return this.ok(config); } } // 2、开发自定义插件(src/index.ts) import { BasePlugin } from "@cool-midway/plugin-cli"; export class CoolPlugin extends BasePlugin { // 插件就绪后触发 async ready() { console.log("插件初始化完成,配置:", this.pluginInfo.config); } // 对外暴露的方法 async chat(message: string) { // 使用插件配置(在后台 UI 填写 appId/appSecret) const { appId, appSecret } = this.pluginInfo.config; return `AI 回复: ${message}`; } // 使用缓存 async getCachedResult(key: string) { let result = await this.cache.get(key); if (!result) { result = await this.fetchData(); await this.cache.set(key, result, 60 * 1000); } return result; } } export const Plugin = CoolPlugin; // plugin.json 配置 // { // "name": "智谱AI", // "key": "zhipu-ai", // "singleton": true, // "version": "1.0.0", // "config": { "appId": "", "appSecret": "" } // } ``` -------------------------------- ### Importing Module Menus (`menu.json`) Source: https://github.com/cool-team-official/cool-admin-midway-docs/blob/main/src/guide/core/module.md Example of defining menu structures for a module using `menu.json`. This includes parent menus and their child menus, specifying properties like name, router, icon, and view path. ```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 } ] } ] ``` -------------------------------- ### Install Redis Cache Dependency (Previous Versions) Source: https://github.com/cool-team-official/cool-admin-midway-docs/blob/main/src/guide/core/cache.md Install the package for Redis caching in previous versions of cool-admin. Note the different package name compared to newer versions. ```bash pnpm i cache-manager-ioredis --save ``` -------------------------------- ### Configure Redis Cluster for Distributed Tasks Source: https://github.com/cool-team-official/cool-admin-midway-docs/blob/main/src/guide/core/task.md Configuration example for connecting to a Redis cluster. This is an alternative to a single Redis instance for distributed task coordination. ```json [ { "host": "192.168.0.103", "port": 7000, }, { "host": "192.168.0.103", "port": 7001, }, { "host": "192.168.0.103", "port": 7002, }, { "host": "192.168.0.103", "port": 7003, }, { "host": "192.168.0.103", "port": 7004, }, { "host": "192.168.0.103", "port": 7005, }, ] ``` -------------------------------- ### Application Control Script Source: https://github.com/cool-team-official/cool-admin-midway-docs/blob/main/src/guide/deploy.md This script handles starting, stopping, and restarting the application based on the provided argument. It includes a default message for incorrect usage. ```bash case "$1" in start) start ;; stop) stop ;; restart) restart ;; *) echo "使用方法: $0 {start|stop|restart}" exit 1 esac exit 0 ``` -------------------------------- ### Plugin Ready Lifecycle Event Source: https://github.com/cool-team-official/cool-admin-midway-docs/blob/main/src/guide/core/plugin.md Implements the `ready` method, which is triggered after plugin initialization. This method is suitable for performing initial setup operations. Note that for singleton plugins, `ready` is called only once. ```typescript import { BasePlugin } from "@cool-midway/plugin-cli"; /** * 描述 */ export class CoolPlugin extends BasePlugin { /** * 插件已就绪,注意:单例插件只会执行一次,非单例插件每次调用都会执行 */ async ready() { console.log("插件就绪"); } } // 导出插件实例, Plugin名称不可修改 export const Plugin = CoolPlugin; ``` -------------------------------- ### Clone Plugin Development Scaffold Source: https://github.com/cool-team-official/cool-admin-midway-docs/blob/main/src/guide/core/plugin.md Instructions for cloning the official plugin development scaffold from GitHub or Gitee to start developing a new plugin. ```bash # github git clone https://github.com/cool-team-official/cool-admin-midway-plugin.git # gitee 如果你的网络不好,可以使用 git clone https://gitee.com/cool-team-official/cool-admin-midway-plugin.git ``` -------------------------------- ### Call Other Plugins Source: https://github.com/cool-team-official/cool-admin-midway-docs/blob/main/src/guide/core/plugin.md Shows how to interact with other plugins within the current plugin using `this.pluginService.getInstance()`. Debugging is limited during development and requires installation in Cool Admin. ```typescript import { BasePlugin } from "@cool-midway/plugin-cli"; /** * 插件实例 */ export class CoolPlugin extends BasePlugin { /** * 调用其他插件 */ async usePlugin() { // 获得其他插件,开发的时候无法调试,只有安装到cool-admin中才能调试 const plugin = await this.pluginService.getInstance("xxx"); console.log(plugin); } } ``` -------------------------------- ### Native Application Deployment Script Source: https://github.com/cool-team-official/cool-admin-midway-docs/blob/main/src/guide/deploy.md 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 # 程序名称(用于提示和查找进程) APP_NAME="cool-admin" # 程序实际启动命令(需替换为你的真实路径) APP_EXEC="./cool-admin-linux" # 保存 PID 的文件路径 PID_FILE="./serve.pid" # 日志输出文件 LOG_FILE="./app.log" ### 功能函数 ### start() { if [ -f "$PID_FILE" ]; then echo "错误:$APP_NAME 已在运行中 (PID: $(cat $PID_FILE))" exit 1 fi echo "正在启动 $APP_NAME ..." nohup $APP_EXEC > $LOG_FILE 2>&1 & echo $! > $PID_FILE echo "✓ 已成功启动 $APP_NAME (PID: $!)" } stop() { if [ ! -f "$PID_FILE" ]; then echo "错误:$APP_NAME 未在运行" exit 1 fi PID=$(cat $PID_FILE) echo "正在停止 $APP_NAME (PID: $PID) ..." kill $PID && rm -f $PID_FILE echo "✓ 已停止 $APP_NAME" } restart() { echo "正在重启 $APP_NAME..." stop sleep 1 # 等待进程完全释放 start } ``` -------------------------------- ### Nginx Configuration for Cool Admin Source: https://github.com/cool-team-official/cool-admin-midway-docs/blob/main/src/guide/deploy.md Example Nginx configuration for proxying requests to the Cool Admin backend and serving the frontend. Includes settings for API proxying, static file serving, and WebSocket connections. ```nginx upstream cool { server 127.0.0.1:8001; } server { ... # 前端打包完放这边 root /home/test/front; # 防止刷新404 location / { try_files $uri $uri/ /index.html; } # 代理服务端地址 访问/api 表示访问服务端接口而不是静态资源 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; #缓存相关配置 #proxy_cache cache_one; #proxy_cache_key $host$request_uri$is_args$args; #proxy_cache_valid 200 304 301 302 1h; #持久化连接相关配置 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特定配置,需要流式响应必备 proxy_buffering off; proxy_cache off; proxy_http_version 1.1; proxy_set_header Connection ''; chunked_transfer_encoding off; #expires 12h; } # socket需额外配置 location /socket { proxy_pass http://cool/socket; proxy_connect_timeout 3600s; #配置点1 proxy_read_timeout 3600s; #配置点2,如果没效,可以考虑这个时间配置长一点 proxy_send_timeout 3600s; #配置点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; } } ``` -------------------------------- ### Importing Data into `dict_type` Table Source: https://github.com/cool-team-official/cool-admin-midway-docs/blob/main/src/guide/core/module.md Example of importing initial data into the `dict_type` table using a `db.json` file. This defines a new dictionary type with a specific key. ```json { "dict_type": [ { "name": "升级类型", "key": "upgradeType" } ] } ``` -------------------------------- ### Lock File for Old Initialization Method (Pre 8.0) Source: https://github.com/cool-team-official/cool-admin-midway-docs/blob/main/src/guide/core/module.md Illustrates the lock files generated after modules are initialized. These files prevent re-initialization on subsequent starts. Deleting these files forces re-initialization. ```tree ├── lock │ ├── db │ └── base.db.lock(base模块) │ └── task.db.lock(task模块) │ ├── menu │ └── base.menu.lock(base模块) │ └── task.menu.lock(task模块) │──package.json ``` -------------------------------- ### Package Backend Application Source: https://github.com/cool-team-official/cool-admin-midway-docs/blob/main/src/guide/core/pkg.md Execute this command in the backend project directory to package the application. If using pnpm, it's recommended to use npm instead. The packaged files will be generated in the 'build' directory. ```bash // If you encounter issues with pnpm commands, it is recommended to use npm commands npm run pkg ``` -------------------------------- ### Run Application Script Source: https://github.com/cool-team-official/cool-admin-midway-docs/blob/main/src/guide/deploy.md Execute the serve.sh script to manage the application lifecycle. Note that v8+ versions automatically find an available port if the default is occupied. ```bash // 启动 ./serve.sh start // 停止 ./serve.sh stop // 重启 ./serve.sh restart ``` -------------------------------- ### Listen for Plugin Ready Event Source: https://github.com/cool-team-official/cool-admin-midway-docs/blob/main/src/guide/core/plugin.md Demonstrates how to listen for the `EVENT_PLUGIN_READY` event to perform actions like plugin initialization when a plugin is ready. ```typescript import { CoolEvent, Event } from "@cool-midway/core"; import { EVENT_PLUGIN_READY } from "../../plugin/service/center"; /** * 插件事件 */ @CoolEvent() export class PluginEvent { /** * 插件已就绪 */ @Event(EVENT_PLUGIN_READY) async onPluginReady() { // 这边写上你要处理的逻辑,例如:初始化插件(有一些插件需要初始化) } } ``` -------------------------------- ### Build and Release Plugin Source: https://github.com/cool-team-official/cool-admin-midway-docs/blob/main/src/guide/core/plugin.md Commands for building and packaging the plugin for distribution. Successful execution results in a '.cool' plugin package in the 'release' directory. ```bash npm run release ``` -------------------------------- ### Build Frontend Static Assets Source: https://github.com/cool-team-official/cool-admin-midway-docs/blob/main/src/guide/core/pkg.md Run this command in the frontend project directory to build static assets. The generated 'dist' directory should then be copied to the backend project's 'public' directory. ```bash # In the frontend project directory npm run build-static ``` -------------------------------- ### 开启多租户配置 Source: https://github.com/cool-team-official/cool-admin-midway-docs/blob/main/src/guide/core/tenant.md 在`src/config/config.default.ts`中配置Cool框架的`tenant`选项,设置`enable: true`来开启多租户功能,并可配置需要过滤多租户的URL。 ```typescript cool: { // 是否开启多租户 tenant: { // 是否开启多租户 enable: true, // 需要过滤多租户的url, 支持通配符,如/admin/**/* 表示admin模块下的所有接口都进行多租户过滤 urls: [], }, } ``` -------------------------------- ### Consume Data from Active Queue Source: https://github.com/cool-team-official/cool-admin-midway-docs/blob/main/src/guide/core/task.md Example of actively retrieving and removing jobs from an active consumer queue. ```typescript // 主动消费队列 @Inject() demoGetterQueue: DemoGetterQueue; const job = await this.demoGetterQueue.getters.getJobs(['wait'], 0, 0, true); // 获得完将数据从队列移除 await job[0].remove(); ``` -------------------------------- ### Plugin Method Signature Source: https://github.com/cool-team-official/cool-admin-midway-docs/blob/main/src/guide/core/plugin.md Example signature for a plugin method that accepts two parameters and returns plugin information. ```typescript /** * 展示插件信息 * @param a 参数a * @param b 参数b * @returns 插件信息 */ async show(a, b) ``` -------------------------------- ### Grant Execute Permissions Source: https://github.com/cool-team-official/cool-admin-midway-docs/blob/main/src/guide/deploy.md Make the serve.sh script executable before running it. ```bash chmod +x serve.sh ``` -------------------------------- ### Implement Database Transaction Source: https://github.com/cool-team-official/cool-admin-midway-docs/blob/main/src/guide/core/db.md Example of using the CoolTransaction decorator for database transactions. Database operations must use the injected queryRunner. ```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, }); } } ``` -------------------------------- ### Get Upload Mode from Server Source: https://github.com/cool-team-official/cool-admin-midway-docs/blob/main/src/guide/core/file.md Retrieve the current file upload mode configured on the server. This is useful for the frontend to adapt its upload strategy. ```typescript import { Get, Inject, Post, Provide } from "@midwayjs/core"; import { CoolController, BaseController } from "@cool-midway/core"; import { Context } from "koa"; import { CoolFile } from "@cool-midway/file"; /** * 文件上传 */ @Provide() @CoolController() export class AppDemoFileController extends BaseController { @Inject() ctx: Context; @Inject() file: CoolFile; @Get("/uploadMode", { summary: "获得上传模式" }) async uploadMode() { return this.ok(await this.file.getMode()); } } ``` -------------------------------- ### Test Plugin Logic (test/index.ts) Source: https://github.com/cool-team-official/cool-admin-midway-docs/blob/main/src/guide/core/plugin.md Demonstrates how to instantiate, initialize, and call methods of a plugin for testing purposes. Requires importing the plugin and its configuration. ```typescript import { Plugin } from "../src/index"; import pluginInfo from "../plugin.json"; // 实例化插件 const indexInstance = new Plugin(); // 初始化插件 indexInstance.init(pluginInfo); // 调用插件方法 indexInstance.demo(); ``` -------------------------------- ### VS Code Auto-Formatting Configuration Source: https://github.com/cool-team-official/cool-admin-midway-docs/blob/main/src/guide/quick.md Configure VS Code to automatically format code using ESLint on save. Ensure the ESLint extension is installed. ```json // #每次保存的时候将代码按eslint格式进行修复 "editor.codeActionsOnSave": { "source.fixAll.eslint": true }, ``` -------------------------------- ### Import BaseEntity from new location Source: https://github.com/cool-team-official/cool-admin-midway-docs/blob/main/src/todo/upgrade.md Starting from v8.0, BaseEntity has been moved from `@cool-midway/core` to `base` module's `entity/base.ts`. This import statement reflects the new path. ```typescript import { BaseEntity } from "../../base/entity/base"; ``` -------------------------------- ### Docker Network and Image Building Source: https://github.com/cool-team-official/cool-admin-midway-docs/blob/main/src/guide/deploy.md Commands to create a Docker network for Cool Admin and build backend and frontend images. ```shell // 创建docker network docker network create cool // 打包后端镜像 docker build -t cool-admin-midway:1.0 . // 打包前端镜像 docker build -t cool-admin-vue:1.0 . ``` -------------------------------- ### Invoke Plugin Method Source: https://github.com/cool-team-official/cool-admin-midway-docs/blob/main/src/guide/core/plugin.md Inject the PluginService to call methods on installed plugins. 'test' is the plugin identifier, 'show' is the method, and subsequent arguments are passed to the plugin method. ```typescript import { CoolController, BaseController } from "@cool-midway/core"; import { PluginService } from "../../../plugin/service/info"; import { Get, Inject } from "@midwayjs/core"; /** * 插件 */ @CoolController() export class OpenDemoPluginController extends BaseController { // 注入插件服务 @Inject() pluginService: PluginService; @Get("/invoke", { summary: "调用插件" }) async invoke() { // test 是插件的标识, show 是插件的方法, 1,2 是传给插件的参数 const result = await this.pluginService.invoke("test", "show", 1, 2); return this.ok(result); } } ``` -------------------------------- ### BullMQ Message Queue Consumer Source: https://context7.com/cool-team-official/cool-admin-midway-docs/llms.txt Define a message queue consumer using the `@CoolQueue` decorator. This example shows how to process messages, with options for automatic retries on failure. ```typescript import { BaseCoolQueue, CoolQueue } from "@cool-midway/task"; @CoolQueue() export class DemoCommQueue extends BaseCoolQueue { async data(job: any, done: any): Promise { console.log("消费队列数据:", job.data); // throw new Error("Failure will trigger automatic retries, default 5 retries"); done(); } } ``` -------------------------------- ### Run Obfuscate Build Command Source: https://github.com/cool-team-official/cool-admin-midway-docs/blob/main/src/guide/other/obfuscate.md Execute this command to build your project with code obfuscation. Ensure your package.json includes the 'build:obfuscate' script. ```bash npm run build:obfuscate ``` -------------------------------- ### Define Elasticsearch Index Mapping Source: https://github.com/cool-team-official/cool-admin-midway-docs/blob/main/src/guide/core/es.md Define a custom Elasticsearch index with its mapping and settings. This example shows how to configure a 'test' index with 'ik_max_word' analyzer for the 'name' field. ```typescript import { CoolEsIndex, ICoolEs, BaseEsIndex } from "@cool-midway/es"; /** * 测试索引 */ @CoolEsIndex({ name: "test", replicas: 0 }) export class TestEsIndex extends BaseEsIndex implements ICoolEs { indexInfo() { return { // 需要安装ik分词器 https://github.com/medcl/elasticsearch-analysis-ik name: { type: "text", analyzer: "ik_max_word", search_analyzer: "ik_max_word", fields: { raw: { type: "keyword", }, }, }, age: { type: "long", }, }; } } ``` -------------------------------- ### Qiniu Cloud Configuration (TypeScript) Source: https://github.com/cool-team-official/cool-admin-midway-docs/blob/main/src/guide/core/file.md Configuration object for integrating with Qiniu Cloud for file storage. Requires setting access keys, bucket name, region, and public domain. ```typescript cool: { file: { mode: MODETYPE.CLOUD, qiniu:{ accessKeyId: string; accessKeySecret: string; bucket: string; region: string; publicDomain: string; } } } ``` -------------------------------- ### Import Cron Component for Built-in Tasks Source: https://github.com/cool-team-official/cool-admin-midway-docs/blob/main/src/guide/core/task.md Import the cron component to enable built-in scheduled task functionality. This setup is required for configuring tasks directly in your code. ```typescript import { Configuration } from "@midwayjs/core"; import * as cron from "@midwayjs/cron"; // 导入模块 import { join } from "path"; @Configuration({ imports: [cron], importConfigs: [join(__dirname, "config")], }) export class AutoConfiguration {} ``` -------------------------------- ### Invoke Plugin Method in Controller Source: https://github.com/cool-team-official/cool-admin-midway-docs/blob/main/src/guide/plugin.md Inject the PluginService to call methods of an installed plugin. The 'test' is the plugin identifier, 'show' is the method name, and subsequent arguments are passed to the plugin method. ```typescript import { CoolController, BaseController } from "@cool-midway/core"; import { PluginService } from "../../../plugin/service/info"; import { Get, Inject } from "@midway/core"; /** * 插件 */ @CoolController() export class OpenDemoPluginController extends BaseController { // 注入插件服务 @Inject() pluginService: PluginService; @Get("/invoke", { summary: "调用插件" }) async invoke() { // test 是插件的标识, show 是插件的方法, 1,2 是传给插件的参数 const result = await this.pluginService.invoke("test", "show", 1, 2); return this.ok(result); } } ``` -------------------------------- ### Server-Side SSE Implementation Source: https://github.com/cool-team-official/cool-admin-midway-docs/blob/main/src/guide/other/sse.md This snippet demonstrates the server-side logic for handling SSE requests. It sets up the necessary headers, creates a stream, and sends data chunks to the client, including handling the end of the stream. ```APIDOC ## POST /open/demo/sse/call ### Description Handles Server-Sent Events (SSE) to stream data from the server to the client in real-time. This is particularly useful for long-running operations like AI model generations, allowing users to see progress. ### Method GET ### Endpoint /open/demo/sse/call ### Parameters #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **Content-Type**: text/event-stream - **Cache-Control**: no-cache - **Connection**: keep-alive - The response body is a stream of events, where each event is formatted as `data: \n\n`. ### Request Example None (This is a server-side implementation) ### Response Example ``` data: {"message": "Processing step 1...", "progress": 10} data: {"message": "Processing step 2...", "progress": 30} ... data: {"message": "Generation complete.", "progress": 100, "isEnd": true} ``` ``` -------------------------------- ### Configure pnpm Registry Source: https://github.com/cool-team-official/cool-admin-midway-docs/blob/main/src/guide/deploy.md Set the pnpm registry to the Taobao mirror for faster package downloads. ```bash pnpm config set registry https://registry.npmmirror.com ```