mic-bot/utils/url_builder.ts

59 lines
1.5 KiB
TypeScript
Raw Permalink Normal View History

2024-10-19 10:00:35 +00:00
export class ReqUrlBuilder {
2024-10-27 09:12:11 +00:00
protected protocol: string = "https";
protected host: string = "";
protected path: string = "";
protected params: { [key: string]: string } = {};
constructor(url?: string) {
const [protocol, host] = url ? url.split("://") : [this.host];
if (host) {
this.protocol = protocol
2024-10-19 10:00:35 +00:00
this.host = host
2024-10-27 09:12:11 +00:00
} else {
this.host = protocol // Default to https if no protocol provided
}
}
setProtocol(protocol: string): ReqUrlBuilder {
this.protocol = protocol.replace("://", "")
return this
}
setHost(host: string): ReqUrlBuilder {
this.host = host
return this
}
setPath(path: string): ReqUrlBuilder {
this.path = path.startsWith("/") ? path : `/${path}`
return this
}
setParamsStr(...params: string[]): ReqUrlBuilder {
params.forEach((param) => {
const [key, value] = param.split("=")
2024-10-19 10:00:35 +00:00
if (key && value) {
2024-10-27 09:12:11 +00:00
this.params[key] = value
2024-10-19 10:00:35 +00:00
}
2024-10-27 09:12:11 +00:00
})
return this
}
setParams(params: { [key: string]: string }): ReqUrlBuilder {
Object.entries(params).forEach(([key, value]) => {
this.params[key] = value
})
return this
}
deleteParam(name: string) {
delete this.params[name]
}
getReqURL(): string {
let queryString = Object.keys(this.params)
.map((key) => `${key}=${encodeURIComponent(this.params[key])}`)
.join("&")
queryString = queryString ? "?" + queryString : ""
return this.protocol+`://`+this.host+this.path+queryString
}
2024-10-19 10:00:35 +00:00
}