Skip to content

Commit

Permalink
feat(serializeParams): now supports optional return types
Browse files Browse the repository at this point in the history
  • Loading branch information
Michael committed Oct 21, 2022
1 parent a5cf0c2 commit a1b9099
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 8 deletions.
9 changes: 8 additions & 1 deletion lib/core/config/request-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import {
argumentIsNotProvided,
isEmpty
} from "../../utils";
import { isValidURL, uriParser } from "../url";
import { isValidURL, serializeParams, uriParser } from "../url";
import { PROTOCOL_REGEXP, HOSTNAME_REGEXP, METHODS } from "../../constants";

type InternalConfig = Omit<InternalUrbexConfiguration, "headers"> & {
Expand Down Expand Up @@ -113,6 +113,13 @@ export class RequestConfig {
cfg.headers = this.$config.headers.normalize(cfg.headers);
}

if (
(hasOwnProperty(cfg, "params") && isString(cfg.params)) ||
cfg.params instanceof URLSearchParams
) {
cfg.params = serializeParams(cfg.params, "object");
}

if (hasOwnProperty(cfg, "url")) {
if (isObject(cfg.url)) {
cfg.url = merge(this.get().url, cfg.url);
Expand Down
27 changes: 20 additions & 7 deletions lib/core/url.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ type URLStringBuilder = Pick<
"protocol" | "hostname" | "port" | "urlMount" | "endpoint" | "params"
>;

type ParamSerializerType = "string" | "object" | "URLSearchParams";

/**
* Test if a url string has a valid protocol.
*
Expand Down Expand Up @@ -125,7 +127,7 @@ export function uriParser(
params: SearchParams = null,
allowEndpoints: boolean = true
): URIComponent {
const serializedParams = serializeParams(params);
const serializedParams = serializeParams(params, "string") as string;

if (isString(uri)) {
if (isValidURL(uri)) {
Expand Down Expand Up @@ -171,17 +173,28 @@ export function uriParser(
);
}

export function serializeParams(params: SearchParams): string {
export function serializeParams(
params: SearchParams,
serializerType: ParamSerializerType = "string"
): Record<string, string> | string {
if (argumentIsNotProvided(params)) {
return null;
}

if (params instanceof URLSearchParams) {
return params.toString();
}

try {
return new URLSearchParams(params).toString();
const searchParams = new URLSearchParams(params);

if (serializerType === "object") {
const params = {};

searchParams.forEach((value, key) => {
params[key] = value;
});

return params;
}

return searchParams.toString();
} catch (error) {
return null;
}
Expand Down

0 comments on commit a1b9099

Please sign in to comment.