# egg-base **Repository Path**: furuihe/egg-base ## Basic Information - **Project Name**: egg-base - **Description**: No description available - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2018-10-25 - **Last Updated**: 2025-11-24 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # @hfr/egg-base Egg.js 基础插件,提供统一的 Controller 扩展、Context 扩展、中间件和工具服务,简化开发流程。 ## 特性 - 🎯 **自定义 Controller** - 扩展基础 Controller,提供便捷的数据库操作方法 - 🔧 **Context 扩展** - 增强 ctx 对象,提供参数校验、分页、事务管理等能力 - 🛡️ **统一异常处理** - exception 中间件统一处理错误响应 - ⏱️ **请求日志** - log-running-time 中间件记录请求运行时长 - 📦 **工具服务** - 提供基础工具类服务 ## 安装 ```bash yarn add @hfr/egg-base ``` ## 配置 在 `config/plugin.js` 中启用插件: ```javascript exports.base = { enable: true, package: '@hfr/egg-base', }; ``` 在 `config/config.default.js` 中配置(可选): ```javascript config.logRunningTime = { format(time) { return `运行时长:${time}毫秒`; }, }; ``` ## 功能说明 ### 1. Controller 扩展 插件会自动替换 `app.Controller`,提供以下便捷方法: #### 属性访问 - `this.models` - 访问所有 Sequelize 模型 - `this.baseUtilService` - 访问基础工具服务 #### 参数校验 - `validateQuery(rules, type)` - 校验查询参数(支持 list、detail、update、delete 类型) - `validateBody(rules)` - 校验请求体参数 - `validateParams(rules, params)` - 校验 URL 参数 #### 分页处理 - `getPageParams()` - 获取分页参数(支持 offset/limit 和 page/pagesize 两种方式) #### 数据库操作 - `transaction(func)` - 数据库事务管理 - `returnListWithCount(promise)` - 返回带总数的列表(Sequelize findAndCountAll) - `returnListWithLength(promise)` - 返回列表(数据长度作为总数) - `returnList(promise, totalPromise)` - 返回列表(自定义总数查询) - `returnListByQuery(promise)` - 返回 SQL 查询结果 - `returnCreate(promise, options)` - 返回创建结果 - `returnBulkCreate(promise)` - 返回批量创建结果 - `returnUpdate(promise, options)` - 返回更新结果 - `returnDetail(promise)` - 返回详情查询结果 - `returnDelete(promise)` - 返回删除结果 #### 响应方法 - `success(data)` - 返回成功响应 ### 2. Context 扩展 在 Controller 和 Service 中可以直接使用以下方法: #### 属性访问 - `ctx.baseUtils` - 访问基础工具服务 #### 响应方法 - `ctx.success(data)` - 返回成功响应(格式:`{ status: 200, data }`) #### 参数校验 - `ctx.validateQuery(rules, type)` - 校验查询参数 - `ctx.validateBody(rules)` - 校验请求体参数 - `ctx.validateParams(rules, params)` - 校验 URL 参数 #### 分页处理 - `ctx.getPageParams()` - 获取分页参数 #### 数据库操作 - `ctx.transaction(func)` - 数据库事务管理 - `ctx.returnListWithCount(promise)` - 返回带总数的列表 - `ctx.returnListWithLength(promise)` - 返回列表(数据长度作为总数) - `ctx.returnList(promise, totalPromise)` - 返回列表(自定义总数查询) - `ctx.returnListByQuery(promise)` - 返回 SQL 查询结果 - `ctx.returnCreate(promise, options)` - 返回创建结果 - `ctx.returnUpdate(promise, options)` - 返回更新结果 - `ctx.returnDetail(promise)` - 返回详情查询结果 - `ctx.returnDelete(promise)` - 返回删除结果 ### 3. 中间件 #### exception 统一异常处理中间件,自动捕获并格式化错误响应。 支持的错误状态码:200, 204, 400, 401, 403, 404, 500 错误对象格式: ```javascript { status: 400, code: 'ERROR_CODE', message: '错误信息' } ``` #### log-running-time 记录请求运行时长的中间件,会在日志中输出请求处理时间。 ### 4. 工具服务 #### ctx.service.utils.base 基础工具服务,提供: - `checkExists(obj, typeId, message)` - 检查对象是否存在,不存在则抛出异常 ## 使用示例 ### Controller 示例 ```javascript const { Controller } = require('egg'); class UserController extends Controller { // 列表查询 async index() { const { ctx } = this; // 校验查询参数 ctx.validateQuery({ name: { type: 'string', required: false } }, 'list'); // 获取分页参数 const { offset, limit } = ctx.getPageParams(); // 查询数据 const promise = this.models.User.findAndCountAll({ where: { name: ctx.query.name }, offset, limit, }); // 返回结果 await ctx.returnListWithCount(promise); } // 详情查询 async show() { const { ctx } = this; // 校验参数 ctx.validateQuery({}, 'detail'); const promise = this.models.User.findByPk(ctx.params.id); await ctx.returnDetail(promise); } // 创建 async create() { const { ctx } = this; // 校验请求体 ctx.validateBody({ name: { type: 'string', required: true }, email: { type: 'email', required: true }, }); const promise = this.models.User.create(ctx.request.body); await ctx.returnCreate(promise); } // 更新 async update() { const { ctx } = this; ctx.validateQuery({}, 'update'); ctx.validateBody({ name: { type: 'string', required: false }, }); const user = await this.models.User.findByPk(ctx.params.id); if (!user) { throw { status: 404, code: 'USER_NOT_FOUND', message: '用户不存在' }; } const promise = user.update(ctx.request.body); await ctx.returnUpdate(promise); } // 删除 async destroy() { const { ctx } = this; ctx.validateQuery({}, 'delete'); const user = await this.models.User.findByPk(ctx.params.id); if (!user) { throw { status: 404, code: 'USER_NOT_FOUND', message: '用户不存在' }; } const promise = user.destroy(); await ctx.returnDelete(promise); } // 使用事务 async transfer() { const { ctx } = this; await ctx.transaction(async (t) => { // 在事务中执行操作 await this.models.Account.update( { balance: this.app.Sequelize.literal('balance - 100') }, { where: { id: 1 }, transaction: t } ); await this.models.Account.update( { balance: this.app.Sequelize.literal('balance + 100') }, { where: { id: 2 }, transaction: t } ); }); ctx.success({ message: '转账成功' }); } } module.exports = UserController; ``` ## 依赖 ### 必需依赖 - `dayjs` - 日期处理库 ### 可选依赖 - `egg-validate` - 参数校验插件(用于 validateQuery、validateBody、validateParams) - `egg-sequelize` - Sequelize ORM 插件(用于数据库操作相关功能) ## 开发 ```bash # 安装依赖 yarn install # 运行测试 yarn test # 代码检查 yarn lint ``` ## License MIT ## 作者 APJ PSD