Created
May 10, 2021 21:46
-
-
Save evgsil/f340254a0e5aaf04a85be695ecac57c6 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
function queryBodyToObject(body: string) { | |
return JSON.parse( | |
body | |
.split('\n') | |
.map((item, idx, arr) => { | |
let str: string; | |
if (item.trim() === '{') return item; | |
if (item.endsWith('{')) return `"${item.slice(0, -1).trim()}": {`; | |
if (item.trim() === '}') { | |
str = item; | |
} else if (item.endsWith('}')) { | |
str = `"${item}"`; | |
} else { | |
str = `"${item.trim()}": true`; | |
} | |
if (idx + 1 < arr.length) { | |
const next = String(arr[idx + 1]).trim(); | |
if (next !== '}') { | |
str += ','; | |
} | |
} | |
return str; | |
}) | |
.join('\n') | |
); | |
} | |
function objectToQueryBody(obj: any, padding: number) { | |
const padStr = new Array(padding).fill(' ').join(''); | |
return JSON.stringify(obj, null, 2) | |
.split(' true') | |
.join('') | |
.split('"') | |
.join('') | |
.split(',') | |
.join('') | |
.split(':') | |
.join('') | |
.split('\n') | |
.map(i => padStr + i) | |
.join('\n') | |
.trim(); | |
} | |
type ConfigItem = { | |
[key: string]: boolean | ConfigItem; | |
}; | |
function applyConfig(query: ConfigItem, config: ConfigItem, strict: boolean) { | |
const configEntries = Object.entries(config); | |
Object.entries(query).forEach(([queryKey, queryValue]) => { | |
const configValue = configEntries.find( | |
([configKey]) => configKey === queryKey | |
)?.[1]; | |
if (typeof queryValue === 'object') { | |
if (typeof configValue === 'object') { | |
applyConfig(queryValue, configValue, strict); | |
} else { | |
if (!configValue) { | |
delete query[queryKey]; | |
} | |
} | |
} else { | |
if ((strict || typeof configValue === 'boolean') && !configValue) { | |
delete query[queryKey]; | |
} | |
} | |
}); | |
} | |
export function trimQuery(query: string, config: ConfigItem, strict = false) { | |
const split = Array.from( | |
/([!,:$()\s\w]*\{[!,:$()\s\w]*)(\{[\s\w{}]*\})(\s*\})/.exec(query) || [] | |
); | |
const queryStart = split[1]; | |
const bodyObj = queryBodyToObject(split[2]); | |
const queryEnd = split[3]; | |
applyConfig(bodyObj, config, strict); | |
const result = `${queryStart} ${objectToQueryBody(bodyObj, 4)}${queryEnd}`; | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment