You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
/**
* 统一API响应格式工具
*
* 作用: 让所有API接口返回统一格式的数据, 方便前端处理
*/
/**
* 成功响应
* @param {*} data - 返回的数据
* @param {string} message - 提示消息
* @returns {object} 格式化的成功响应
*/
const success = ( data = null , message = '操作成功' ) => {
return {
success : true ,
message ,
data ,
timestamp : new Date ( ) . toISOString ( ) // ISO格式的时间戳
} ;
} ;
/**
* 错误响应
* @param {string} message - 错误消息
* @param {number} code - 错误代码(可选)
* @returns {object} 格式化的错误响应
*/
const error = ( message = '操作失败' , code = null ) => {
return {
success : false ,
message ,
... ( code && { code } ) , // 如果有错误代码,就添加到响应中
timestamp : new Date ( ) . toISOString ( )
} ;
} ;
/**
* 分页响应
* @param {array} data - 数据列表
* @param {number} total - 总记录数
* @param {number} page - 当前页码
* @param {number} pageSize - 每页数量
* @returns {object} 格式化的分页响应
*/
const pagination = ( data , total , page , pageSize ) => {
return {
success : true ,
data : {
list : data , // 当前页的数据
pagination : {
total , // 总记录数
page : parseInt ( page ) , // 当前页码
pageSize : parseInt ( pageSize ) , // 每页数量
totalPages : Math . ceil ( total / pageSize ) // 总页数
}
} ,
timestamp : new Date ( ) . toISOString ( )
} ;
} ;
// 导出所有函数
module . exports = {
success ,
error ,
pagination
} ;