sharkey/packages/backend/src/misc/prelude/url.ts

19 lines
736 B
TypeScript
Raw Normal View History

/* obj
* 1.
* 2. undefinedの時はクエリを付けない
* new URLSearchParams(obj)
*/
2021-11-12 10:52:10 +09:00
export function query(obj: Record<string, unknown>): string {
const params = Object.entries(obj)
.filter(([, v]) => Array.isArray(v) ? v.length : v !== undefined)
.reduce((a, [k, v]) => (a[k] = v, a), {} as Record<string, any>);
return Object.entries(params)
2021-10-01 02:25:57 +09:00
.map((e) => `${e[0]}=${encodeURIComponent(e[1])}`)
.join('&');
}
export function appendQuery(url: string, query: string): string {
return `${url}${/\?/.test(url) ? url.endsWith('?') ? '' : '&' : '?'}${query}`;
}