Created
November 7, 2020 17:07
-
-
Save Pacheco95/f3468408e2629f077394f1e65c1a7c2c to your computer and use it in GitHub Desktop.
Schema based query string parser
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const assert = require("assert"); | |
const objectify = (o, [k, v]) => ({ ...o, [k]: v }); | |
function parseFromURL(schema, url = window.location.search) { | |
const searchParams = new URLSearchParams(url); | |
return Object.entries(schema) | |
.map(([par, { def }]) => [par, searchParams.get(par) ?? def ?? undefined]) | |
.map(([par, val]) => [par, schema[par].transform?.(val) ?? val]) | |
.reduce(objectify, {}); | |
} | |
// a=1&b=null&c=undefined&d=&e=test | |
const url = new URLSearchParams({ | |
a: 1, | |
b: null, | |
c: undefined, | |
d: "", | |
e: "test", | |
f: JSON.stringify({ name: "test" }), | |
}).toString(); | |
const schema = { | |
a: { | |
def: 5, | |
transform: String, | |
}, | |
b: {}, | |
c: {}, | |
d: { | |
def: "undefined", | |
transform: Boolean, | |
}, | |
f: { | |
def: { | |
name: "test", | |
}, | |
transform: JSON.parse, | |
}, | |
}; | |
const { a, b, c, d, e, f, g, h } = parseFromURL(schema, url); | |
assert(a === "1"); | |
assert(b === "null"); | |
assert(c === "undefined"); | |
assert(d === false); | |
assert(e === undefined); | |
assert(f.name === "test"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment