Skip to content

Commit

Permalink
test: add test for param encoding
Browse files Browse the repository at this point in the history
  • Loading branch information
Bekacru committed Jul 26, 2024
1 parent dba2d82 commit ad834b6
Show file tree
Hide file tree
Showing 3 changed files with 82 additions and 13 deletions.
13 changes: 12 additions & 1 deletion packages/better-fetch/src/test/fetch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -429,7 +429,18 @@ describe("url", () => {
baseURL: "http://localhost:4001",
});
expect(url.toString()).toBe(
"http://localhost:4001/query?id=%2320&name=test+2",
"http://localhost:4001/query?id=%2320&name=test%202",
);
});

it("should encode dynamic params", async () => {
const url = getURL("/param/:id/:space", {
params: {
id: "#test",
space: "item 1",
},
baseURL: "http://localhost:4001",
});
expect(url.toString()).toBe("http://localhost:4001/param/%23test/item%201");
});
});
15 changes: 3 additions & 12 deletions packages/better-fetch/src/url.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,17 +31,7 @@ export function getURL(url: string, option?: BetterFetchOption) {

if (!basePath.endsWith("/")) basePath += "/";
let [path, urlQuery] = url.replace(basePath, "").split("?");
const existingQuery =
urlQuery?.split("&").reduce(
(acc, param) => {
const [key, value] = param.split("=");
acc[key] = decodeURIComponent(value);
return acc;
},
{} as Record<string, string>,
) || {};
query = { ...existingQuery, ...query };
const queryParams = new URLSearchParams();
const queryParams = new URLSearchParams(urlQuery);
for (const [key, value] of Object.entries(query || {})) {
queryParams.set(key, String(value));
}
Expand All @@ -61,7 +51,8 @@ export function getURL(url: string, option?: BetterFetchOption) {

path = path.split("/").map(encodeURIComponent).join("/");
if (path.startsWith("/")) path = path.slice(1);
const queryParamString = queryParams.size > 0 ? `?${queryParams}` : "";
let queryParamString =
queryParams.size > 0 ? `?${queryParams}`.replace(/\+/g, "%20") : "";
const _url = new URL(`${path}${queryParamString}`, basePath);
return _url;
}
67 changes: 67 additions & 0 deletions packages/better-fetch/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,73 @@ export function getHeaders(opts?: BetterFetchOption) {
return headers;
}

export function getURL(url: string, options?: BetterFetchOption) {
if (url.startsWith("@")) {
const m = url.toString().split("@")[1].split("/")[0];
if (methods.includes(m)) {
url = url.replace(`@${m}/`, "/");
}
}
let _url: string | URL;
try {
if (url.startsWith("http")) {
_url = url;
} else {
let baseURL = options?.baseURL;
if (baseURL && !baseURL?.endsWith("/")) {
baseURL = baseURL + "/";
}
if (url.startsWith("/")) {
_url = new URL(url.substring(1), baseURL);
} else {
_url = new URL(url, options?.baseURL);
}
}
} catch (e) {
if (e instanceof TypeError) {
if (!options?.baseURL) {
throw TypeError(
`Invalid URL ${url}. Are you passing in a relative url but not setting the baseURL?`,
);
}
throw TypeError(
`Invalid URL ${url}. Please validate that you are passing the correct input.`,
);
}
throw e;
}

/**
* Dynamic Parameters.
*/
if (options?.params) {
if (Array.isArray(options?.params)) {
const params = options?.params
? Array.isArray(options.params)
? `/${options.params.join("/")}`
: `/${Object.values(options.params).join("/")}`
: "";
_url = _url.toString().split("/:")[0];
_url = `${_url.toString()}${params}`;
} else {
for (const [key, value] of Object.entries(options?.params)) {
_url = _url.toString().replace(`:${key}`, String(value));
}
}
}
const __url = new URL(_url);
/**
* Query Parameters
*/
const queryParams = options?.query;
if (queryParams) {
for (const [key, value] of Object.entries(queryParams)) {
__url.searchParams.append(key, String(value));
}
}
return __url;
}

export function detectContentType(body: any) {
if (isJSONSerializable(body)) {
return "application/json";
Expand Down

0 comments on commit ad834b6

Please sign in to comment.