1.0.1 • Published 6 months ago

@alexfalconflores/better-url v1.0.1

Weekly downloads
-
License
MIT
Repository
github
Last release
6 months ago

🚀 Installation

npm install @alexfalconflores/better-url

✨ Features

  • Based on native object URL
  • Seamless API with method chaining
  • Authentication support (auth)
  • Dynamic paths with normalization
  • Query parameters (query, setQuery, tryQuery, etc.)
  • Fragments (#anchor)
  • Generic typing for your query parameters

📦 Examples of use

⚙️ Create a new instance

import BetterURL from "better-url";

type Params = {
  search: string;
  page?: number;
  sort?: "asc" | "desc";
};

const url = new BetterURL<Params>("https://example.com");

🔐 auth

url.auth("admin", "1234");
// https://admin:1234@example.com

🔧 portNumber y path

url.portNumber(8080).path("api/v1/users");
// https://admin:1234@example.com:8080/api/v1/users

🧭 query

url.query("search", "john").query("sort", "asc");
// https://.../api/v1/users?search=john&sort=asc

❔tryQuery

const optionalPage = undefined;

url.tryQuery("page", optionalPage); // No se añade nada

🔁 (setQuery, trySetQuery)

url.setQuery("search", "doe").trySetQuery("page", 2);
// ?search=doe&page=2

❌ (removeQuery, clearQuery)

url.removeQuery("sort");
url.clearQuery();
// ? (queda vacío)

🧩 (fragment)

url.fragment("top");
// #top

🧪 Final result

console.log(url.toString());
// https://admin:1234@example.com:8080/api/v1/users?search=doe&page=2#top

🧠 Strong typing

type QueryParams = {
  search: string;
  page: number;
};

url.query("search", "hello"); // ✅
url.query("unknown", "value"); // ❌ Error: 'unknown' no está en Params

🧰 Available methods

MethodDescription
.auth(user, pass)Add credentials to the URL
.portNumber(port)Defines the port
.path(path)Add routes (normalize /)
.query(key, value)Add a query param (use TQueryParams typing)
.tryQuery(...)Add a query only if the value is not null/undefined
.setQuery(...)Sets or replaces a query
.trySetQuery(...)Same as .setQuery but conditional
.removeQuery(key)Removes a query parameter
.clearQuery()Deletes all parameters
.fragment(str)Add or replace a #fragment

👤 Autor

Alex Stefano Falcon Flores

📄 License

This project is licensed under the MIT license. See the LICENSE file for more details.

⭐ Do you like it?

Give the repo a star to support the project! And if you use it in your projects, I'd love to see it! 🎉