qs.uts 5.16 KB
/**
 * 简化版 qs.stringify(从 gl_tape/lib/qs.js 核心逻辑提取)
 * 仅支持简单对象序列化,不处理复杂嵌套
 */

export type Encoder = (str: string) => string
export type Sorter = (a: any, b: any) => number
export type GenerateArrayPrefix = (prefix: string, key: string) => string
export type Formatter = (str: string) => string
export type SerializeDate = (date: Date) => string
export type Filter = (prefix: string, value: any) => any

export type StringifyOptions = {
    allowDots?: boolean
    encoder?: Encoder
    encodeValuesOnly?: boolean
    filter?: any // Function | Array<string>
    formatter?: Formatter
    generateArrayPrefix?: GenerateArrayPrefix
    prefix?: string
    serializeDate?: SerializeDate
    skipNulls?: boolean
    sort?: Sorter
    strictNullHandling?: boolean
}

function defaultEncoder(str: string): string {
	const res = encodeURIComponent(str);
	return res ?? str;
}

function defaultGenerateArrayPrefix(p: string, k: string): string {
	return `${p}[${k}]`;
}

function defaultFormatter(str: string): string {
	return str;
}

function defaultSerializeDate(date: Date): string {
	return date.toISOString();
}

function stringifyRecursive(
	obj: any | null,
	options: StringifyOptions
): string {
	const prefix = options.prefix ?? "";
	const encoder = options.encoder !== null ? options.encoder : (str: string): string => defaultEncoder(str);
	const filter = options.filter;
	const sort = options.sort;
	const strictNullHandling = options.strictNullHandling ?? false;
	const skipNulls = options.skipNulls ?? false;
	const encodeValuesOnly = options.encodeValuesOnly ?? false;
	const generateArrayPrefix = options.generateArrayPrefix !== null ? options.generateArrayPrefix : (p: string, k: string): string => defaultGenerateArrayPrefix(p, k);
	const allowDots = options.allowDots ?? false;
	const formatter = options.formatter !== null ? options.formatter : (str: string): string => defaultFormatter(str);
	const serializeDate = options.serializeDate !== null ? options.serializeDate : (date: Date): string => defaultSerializeDate(date);

	let processedObj: any | null = obj;

	if (typeof filter === "function") {
		const filterFn = filter as Filter;
		// UTS requires parameter types to match exactly, but 'obj' is 'any | null'
		// and Filter expects 'any'. Casting 'obj' to 'any' is safe here.
		processedObj = filterFn(prefix, obj as any);
	} else if (obj instanceof Date) {
		processedObj = serializeDate(obj);
	} else if (obj === null) {
		if (strictNullHandling) {
			return encoder(prefix);
		}
		processedObj = "";
	}

	if (typeof processedObj === "string" ||
        typeof processedObj === "number" ||
        typeof processedObj === "boolean") {
		const keyValue = encodeValuesOnly ? prefix : encoder(prefix);
		const valueStr = typeof processedObj === "string" ? processedObj as string : `${processedObj}`;
		return `${formatter(keyValue)}=${formatter(encoder(valueStr))}`;
	}

	const values: string[] = [];

	if (processedObj === null) {
		return "";
	}

	let objKeys: string[] = [];
	let targetObj: any | null = processedObj;

	if (Array.isArray(filter)) {
		objKeys = filter as string[];
		// If filter is array, we still need to know how to access processedObj
		// If processedObj is not array/map, we might need to convert it to be accessible
		if (!Array.isArray(processedObj) && !(processedObj instanceof UTSJSONObject)) {
			targetObj = new UTSJSONObject(processedObj);
		}
	} else {
		// if (processedObj !== null) {
		if (Array.isArray(processedObj)) {
			const arr = processedObj as any[];
			for (let i = 0; i < arr.length; i++) {
				objKeys.push(`${i}`);
			}
		} else if (processedObj instanceof UTSJSONObject) {
			const objMap = (processedObj as UTSJSONObject).toMap();
			objMap.forEach((_, key) => {
				objKeys.push(key);
			});
		} else {
			const json = new UTSJSONObject(processedObj);
			targetObj = json;
			const objMap = json.toMap();
			objMap.forEach((_, key) => {
				objKeys.push(key);
			});
		}
		if (sort !== null) {
			objKeys = objKeys.sort(sort);
		}
		// }
	}

	for (const key of objKeys) {
		let value: any | null = null;

		if (Array.isArray(targetObj)) {
			const idx = Number.parseInt(key);
			if (!Number.isNaN(idx)) {
				value = (targetObj as any[])[idx];
			}
		} else {
			value = (targetObj as UTSJSONObject)[key];
		}

		if (skipNulls && value === null) {
			continue;
		}

		const nextPrefix = Array.isArray(targetObj)
			? (prefix !== "" ? generateArrayPrefix(prefix, key) : key)
			: (prefix !== "" ? prefix + (allowDots ? `.${key}` : `[${key}]`) : key);

		const newOptions: StringifyOptions = {
			prefix: nextPrefix,
			encoder,
			filter,
			sort,
			strictNullHandling,
			skipNulls,
			encodeValuesOnly,
			generateArrayPrefix,
			allowDots,
			serializeDate,
			formatter
		};

		const result = stringifyRecursive(value, newOptions);
		if (result !== "") {
			values.push(result);
		}
	}

	return values.join("&");
}

/**
 * 将对象序列化为 query string
 * @param obj 要序列化的对象
 * @param options 配置选项
 * @returns 序列化后的字符串,如 "key1=val1&key2=val2"
 */
export function stringify(
	obj: UTSJSONObject,
	options: StringifyOptions = {} as StringifyOptions
): string {
	return stringifyRecursive(obj, options);
}