stringify.ts 3.27 KB
/**
 * 自建的查询字符串序列化函数,替代 qs.stringify
 * 支持类似 qs 的配置选项
 */

export interface StringifyOptions {
  arrayFormat?: 'indices' | 'brackets' | 'repeat' | 'comma';
  allowDots?: boolean;
  encodeValuesOnly?: boolean;
  encode?: boolean;
  delimiter?: string;
}

/**
 * 将对象序列化为查询字符串
 * @param obj 要序列化的对象
 * @param options 序列化选项
 * @returns 查询字符串
 */
export function stringify(obj: any, options: StringifyOptions = {}): string {
  const {
    arrayFormat = 'indices',
    allowDots = false,
    encodeValuesOnly = false,
    encode = true,
    delimiter = '&'
  } = options;

  const pairs: string[] = [];

  function addPair(key: string, value: any, keyPrefix?: string) {
    const finalKey = keyPrefix ? `${keyPrefix}${allowDots ? '.' : '['}${key}${allowDots ? '' : ']'}` : key;
    
    if (value === null) {
      pairs.push(encode ? `${encodeURIComponent(finalKey)}=null` : `${finalKey}=null`);
    } else if (value === undefined) {
      pairs.push(encode ? `${encodeURIComponent(finalKey)}=undefined` : `${finalKey}=undefined`);
    } else if (typeof value === 'boolean') {
      pairs.push(encode ? `${encodeURIComponent(finalKey)}=${value}` : `${finalKey}=${value}`);
    } else if (typeof value === 'number') {
      pairs.push(encode ? `${encodeURIComponent(finalKey)}=${value}` : `${finalKey}=${value}`);
    } else if (Array.isArray(value)) {
      value.forEach((item, index) => {
        let arrayKey: string;
        switch (arrayFormat) {
          case 'indices':
            arrayKey = `${finalKey}[${index}]`;
            break;
          case 'brackets':
            arrayKey = `${finalKey}[]`;
            break;
          case 'repeat':
            arrayKey = finalKey;
            break;
          case 'comma':
            // 对于 comma 格式,我们将在最后处理
            return;
          default:
            arrayKey = `${finalKey}[${index}]`;
        }
        
        if (typeof item === 'object' && item !== null) {
          serializeObject(item, arrayKey);
        } else {
          const encodedKey = encode && !encodeValuesOnly ? encodeURIComponent(arrayKey) : arrayKey;
          const encodedValue = encode ? encodeURIComponent(String(item)) : String(item);
          pairs.push(`${encodedKey}=${encodedValue}`);
        }
      });
      
      // 处理 comma 格式
      if (arrayFormat === 'comma' && value.length > 0) {
        const encodedKey = encode && !encodeValuesOnly ? encodeURIComponent(finalKey) : finalKey;
        const encodedValues = value.map(item => encode ? encodeURIComponent(String(item)) : String(item));
        pairs.push(`${encodedKey}=${encodedValues.join(',')}`);
      }
    } else if (typeof value === 'object' && value !== null) {
      serializeObject(value, finalKey);
    } else {
      const encodedKey = encode && !encodeValuesOnly ? encodeURIComponent(finalKey) : finalKey;
      const encodedValue = encode ? encodeURIComponent(String(value)) : String(value);
      pairs.push(`${encodedKey}=${encodedValue}`);
    }
  }

  function serializeObject(obj: any, prefix?: string) {
    Object.keys(obj).forEach(key => {
      const value = obj[key];
      addPair(key, value, prefix);
    });
  }

  serializeObject(obj);
  
  return pairs.join(delimiter);
}