mic-bot/utils/url_builder.ts
2024-10-19 12:00:35 +02:00

63 lines
1.7 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.split("://");
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
}
private addParam(key: string, value: string): ReqUrlBuilder {
if (key && value) {
this.params[key] = value;
}
return this
}
setParams(...params: string[]): ReqUrlBuilder {
params.forEach((param) => {
const [key, value] = param.split("=")
if (key && value) {
this.addParam(key, value)
}
})
return this
}
setQueryParams(queryParams: { [key: string]: string }): ReqUrlBuilder {
Object.entries(queryParams).forEach(([key, value]) => {
this.addParam(key, value)
})
return this
}
getReqURL(): string {
const queryString = Object.keys(this.params)
.map((key) => `${key}=${encodeURIComponent(this.params[key])}`)
.join("&")
return `${this.protocol}://${this.host}${this.path}${
queryString ? "?" + queryString : ""
}`
}
}