UNPKG

openchain-sdk-yxl-ts

Version:

OpenChain SDK for browser

133 lines (120 loc) 3.35 kB
import errors from '../exception/index.js'; /** * 日志操作相关的方法集合 * 这些方法将被混入到 Operation 类中 */ class LogOperations { /** * 验证日志主题 * @private * @param {string} topic - 日志主题 * @returns {boolean} 是否有效 */ _isValidLogTopic(topic) { return typeof topic === 'string' && topic.length <= 128; } /** * 验证日志数据 * @private * @param {Array<string>} datas - 日志数据数组 * @returns {Object} 验证结果 */ _validateLogDatas(datas) { if (!Array.isArray(datas)) { return { valid: false, error: 'INVALID_LOG_DATA_ERROR' }; } for (const item of datas) { if (typeof item !== 'string' || item.length > 1024) { return { valid: false, error: 'INVALID_LOG_DATA_ERROR' }; } } return { valid: true }; } /** * 创建日志操作 * @param {Object} args - 日志参数 * @param {string} [args.sourceAddress] - 源地址 * @param {string} args.topic - 日志主题 * @param {Array<string>} args.datas - 日志数据数组 * @param {string} [args.metadata] - 元数据 * @returns {Object} 操作结果 */ createLogOperation(args) { try { // 参数类型检查 if (Array.isArray(args) || typeof args !== 'object' || args === null) { return this._responseError(errors.INVALID_ARGUMENTS); } // 参数验证模式 const schema = { sourceAddress: { required: false, address: true, }, topic: { required: true, string: true, }, datas: { required: true, array: true, }, metadata: { required: false, string: true, }, }; // 基本参数验证 const validation = this._validate(args, schema); if (!validation.tag) { return this._responseError(errors[validation.msg]); } // 验证日志主题 if (!this._isValidLogTopic(args.topic)) { return this._responseError(errors.INVALID_LOG_TOPIC_ERROR); } // 验证日志数据 const datasValidation = this._validateLogDatas(args.datas); if (!datasValidation.valid) { return this._responseError(errors[datasValidation.error]); } // 构建操作数据 return this._responseData({ operation: { type: 'createLog', data: this._sanitizeOperationData(args), }, }); } catch (err) { console.error('Error in createLogOperation:', err); throw err; } } /** * 清理操作数据,移除未定义的字段 * @private * @param {Object} data - 原始数据 * @returns {Object} 清理后的数据 */ _sanitizeOperationData(data) { return Object.entries(data).reduce((acc, [key, value]) => { if (value !== undefined && value !== null) { acc[key] = value; } return acc; }, {}); } } // 导出操作方法 export default { createLogOperation: LogOperations.prototype.createLogOperation, _isValidLogTopic: LogOperations.prototype._isValidLogTopic, _validateLogDatas: LogOperations.prototype._validateLogDatas, _sanitizeOperationData: LogOperations.prototype._sanitizeOperationData, };