mic-bot/utils/url_builder.ts

59 lines
1.5 KiB
TypeScript

export class ReqUrlBuilder {
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
this.host = host
} 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("=")
if (key && value) {
this.params[key] = value
}
})
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
}
}