Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Standardize POST canonicalization query strings with pywb #68

Merged
merged 2 commits into from
Aug 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "warcio",
"version": "2.2.1",
"version": "2.2.2",
"keywords": [
"WARC",
"web archiving"
Expand Down
40 changes: 34 additions & 6 deletions src/lib/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,13 +157,41 @@ export function jsonToQueryParams(json: string | any, ignoreInvalid = true) {
return key + "." + ++dupes[key] + "_";
};

try {
JSON.stringify(json, (k, v) => {
if (!["object", "function"].includes(typeof v)) {
q.set(getKey(k), v);
const parser = (jsonObj: object, key="") => {
let queryValue = "";

// if object, attempt to recurse through key/value pairs
if (typeof(jsonObj) === "object" && !(jsonObj instanceof Array)) {
try {
for (const [key, value] of Object.entries(jsonObj)) {
parser(value, key);
}
} catch (e) {
// special case for null
if (jsonObj === null) {
queryValue = "null";
}
}
}

// if array, recurse through values, re-using key
else if (jsonObj instanceof Array) {
for (let i=0; i < jsonObj.length; i++) {
parser(jsonObj[i], key);
}
return v;
});
}

if (["string", "number", "boolean"].includes(typeof(jsonObj))) {
queryValue = jsonObj.toString();
}

if (queryValue) {
q.set(getKey(key), queryValue);
}
};

try {
parser(json);
} catch (e) {
if (!ignoreInvalid) {
throw e;
Expand Down
16 changes: 16 additions & 0 deletions test/testUtils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,22 @@ describe("utils", () => {
).toBe("abc=def&data=bar&bar=2&a=3&a.2_=4&bar.2_=123&a.3_=5");
});

test("another json with more complicated data", () => {
expect(
toQuery({
"type": "event",
"id": 44.0,
"float": 35.7,
"values": [true, false, null],
"source": {
"type": "component",
"id": "a+b&c= d",
"values": [3, 4]
}
})
).toBe("type=event&id=44&float=35.7&values=true&values.2_=false&values.3_=null&type.2_=component&id.2_=a%2Bb%26c%3D+d&values.4_=3&values.5_=4");
});

test("post-to-get empty", () => {
const request = {
postData: "",
Expand Down
Loading