| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798 |
- import {
- DATA_MODEL_ERROR_REQUIRED_KEY_MISSING,
- DATA_MODEL_ERROR_TRY_CONVERT_BAD_TYPE,
- DATA_MODEL_ERROR_PRINT_SOURCE,
- DATA_MODEL_ERROR_ARRAY_REQUIRED_KEY_MISSING,
- DATA_MODEL_ERROR_ARRAY_IS_NOT_ARRAY,
- DATA_MODEL_ERROR_MUST_PROVIDE_SIDE,
- DATA_MODEL_ERROR_REQUIRED_KEY_NULL,
- DataConverter,
- DataErrorFormatUtils,
- defaultDataErrorFormatHandler
- } from "@imengyu/js-request-transform";
- function setErrorFormatter() {
- DataErrorFormatUtils.setFormatHandler((error, data) => {
- switch (error) {
- case DATA_MODEL_ERROR_REQUIRED_KEY_MISSING:
- return `字段 ${data.sourceKey} 必填但未提供。 来源 ${data.source}; 对象 ${data.objectName} ${data.serverKey ? ('服务器应传字段: ' + data.serverKey) : ''}`;
- case DATA_MODEL_ERROR_TRY_CONVERT_BAD_TYPE:
- return `尝试将 ${data.sourceType} 转换为 ${data.targetType}。`;
- case DATA_MODEL_ERROR_PRINT_SOURCE:
- return `来源: ${data.objectName}.`;
- case DATA_MODEL_ERROR_ARRAY_REQUIRED_KEY_MISSING:
- return `转换数组模型失败: 需要的字段 ${data.sourceKey} 未提供。`
- case DATA_MODEL_ERROR_ARRAY_IS_NOT_ARRAY:
- return `转换数组模型失败: 需要的字段 ${data.sourceKey} 不是数组类型。`
- case DATA_MODEL_ERROR_MUST_PROVIDE_SIDE:
- return `转换字段 ${data.key} 失败: 必须提供 ${data.direction} 侧数据。`;
- case DATA_MODEL_ERROR_REQUIRED_KEY_NULL:
- return `转换字段 ${data.key} 失败: 必填字段 ${data.key} 未提供或者为 null。`;
- }
- return defaultDataErrorFormatHandler(error, data);
- });
- }
- export function registryConvert() {
- setErrorFormatter();
- DataConverter.registerConverter({
- key: 'SplitCommaArray',
- targetType: 'splitCommaArray',
- converter: (source, key, type) => {
- if (typeof source === 'string')
- return {
- success: true,
- result: source?.split(',') || [],
- }
- return {
- success: false,
- convertFailMessage: `[${key}] 不是字符串类型`,
- };
- }
- })
- DataConverter.registerConverter({
- key: 'CommaArrayMerge',
- targetType: 'commaArrayMerge',
- converter: (source, key, type) => {
- if (source instanceof Array)
- return {
- success: true,
- result: source?.join(',') || '',
- }
- return {
- success: false,
- convertFailMessage: `[${key}] 不是数组类型`,
- };
- }
- })
- DataConverter.registerConverter({
- key: 'ForceArray',
- targetType: 'forceArray',
- converter: (source, key, type) => {
- if (source instanceof Array)
- return {
- success: true,
- result: source,
- }
- if (typeof source === 'object' && source !== null) {
- const arr = []
- for (const key in source) {
- arr.push((source as Record<string, any>)[key])
- }
- return {
- success: true,
- result: arr,
- }
- }
- if (typeof source === 'string')
- return {
- success: true,
- result: source.split(','),
- }
- return {
- success: false,
- convertFailMessage: `[${key}] 不是数组类型`,
- };
- }
- })
- }
|