simple-fetch-ts
Version:
`simple-fetch-ts` is a TypeScript library designed to simplify HTTP requests using a builder-pattern approach. It provides a fluent API for creating, configuring, and executing various HTTP methods (`GET`, `POST`, `PUT`, `PATCH`, `DELETE`) with type safet
47 lines (46 loc) • 1.78 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.isValidURL = exports.serializeQueryParams = exports.validateQueryParams = void 0;
const query_param_error_1 = require("../errors/query-param-error");
const validateQueryParams = (params) => {
if (typeof params !== "object" || params === null || Array.isArray(params)) {
throw new query_param_error_1.InvalidQueryParamObjectError(params);
}
for (const [key, value] of Object.entries(params)) {
if (typeof value !== "string" &&
typeof value !== "number" &&
!(Array.isArray(value) &&
value.every((item) => typeof item === "string" || typeof item === "number"))) {
throw new query_param_error_1.InvalidQueryParamError(key, value);
}
}
};
exports.validateQueryParams = validateQueryParams;
const serializeQueryParams = (params, lowerCaseKeys = false) => {
(0, exports.validateQueryParams)(params);
return Object.entries(params)
.map(([key, value]) => {
const finalKey = lowerCaseKeys ? key.toLowerCase() : key;
if (value === null || value === undefined) {
throw new query_param_error_1.InvalidQueryParamError(key, value);
}
if (Array.isArray(value)) {
return value
.map((item) => `${encodeURIComponent(finalKey)}=${encodeURIComponent(String(item))}`)
.join("&");
}
return `${encodeURIComponent(finalKey)}=${encodeURIComponent(String(value))}`;
})
.join("&");
};
exports.serializeQueryParams = serializeQueryParams;
const isValidURL = (url) => {
try {
new URL(url);
return true;
}
catch {
return false;
}
};
exports.isValidURL = isValidURL;