Created
February 24, 2022 17:57
-
-
Save Helveg/2663c8ef09bc0c27c68419c6d06215ea to your computer and use it in GitHub Desktop.
Deep and nested query parameters for Angular, for use with things like Strapi
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
class DeepQuery { | |
constructor(public query: any) { | |
} | |
private isObj(obj: any): boolean { | |
return ( | |
typeof obj === 'object' && | |
obj !== null | |
) | |
} | |
private toQPK(crumbs: string[]): string { | |
if (crumbs.length == 0) { | |
throw new Error(`Parameter without key`) | |
} | |
return crumbs[0] + crumbs.slice(1).map(s => `[${s}]`).join(""); | |
} | |
private parse(obj: any, crumbs: string[] = [], memo: {[key: string]: any} = {}) { | |
if (!this.isObj(obj)) { | |
memo[this.toQPK(crumbs)] = obj; | |
} else if (Array.isArray(obj)) { | |
for (let i = 0; i < obj.length; i++) { | |
crumbs.push(i.toString()); | |
this.parse(obj[i], crumbs, memo); | |
crumbs.pop(); | |
} | |
} else { | |
for (let key in obj) { | |
if (obj.hasOwnProperty(key)) { | |
crumbs.push(key); | |
this.parse(obj[key], crumbs, memo) | |
crumbs.pop(); | |
} | |
} | |
} | |
return memo; | |
} | |
public encode() { | |
return this.parse(this.query); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment