qs.uts
5.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
/**
* 简化版 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);
}