'use strict'; /** * 对外通用回调接口(OpenAPI 协议)的响应封装。 * * 协议与 WMS /openapi 完全对齐(见 D:\wms\app\lib\api_response.js), * 便于双方用同一套客户端解析返回: * 成功:{ flag: 'success', code: 1, message, data, timestamp } * 失败:{ flag: 'failure', code, message, data: null, timestamp } * * 注意:本文件只服务于「对外」接口,OMS 内部 RESTful 接口仍使用 * { code: 0, message, data } 结构,两者不要混用。 */ /** * 当前时间戳(Unix 秒) * @return {Number} 秒级时间戳 */ function nowTimestamp() { return Math.floor(Date.now() / 1000); } /** * 判断是否普通对象(非数组、非 null) * @param {*} value 任意值 * @return {Boolean} 是否普通对象 */ function isObject(value) { return value && typeof value === 'object' && !Array.isArray(value); } /** * 组装对外接口成功响应 * @param {*} payload 业务数据,写入 data * @param {String} [message] 提示信息 * @return {Object} { flag, code, message, data, timestamp } */ function toSuccess(payload, message = 'ok') { return { flag: 'success', code: 1, message, data: payload === undefined ? null : payload, timestamp: nowTimestamp(), }; } /** * 组装对外接口失败响应 * @param {Object} options 失败信息 * @param {String} [options.message] 提示信息 * @param {Number} [options.code] 业务错误码,默认与 HTTP 状态码一致 * @param {*} [options.data] 附加数据,默认 null * @return {Object} { flag, code, message, data, timestamp } */ function toFailure({ message = '请求失败', code, data = null } = {}) { return { flag: 'failure', code: typeof code === 'number' ? code : 500, message, data: isObject(data) || Array.isArray(data) ? data : null, timestamp: nowTimestamp(), }; } module.exports = { toSuccess, toFailure, nowTimestamp };