All Projects → balazsbotond → Urlcat

balazsbotond / Urlcat

Licence: mit
A URL builder library for JavaScript.

Programming Languages

typescript
32286 projects

Projects that are alternatives of or similar to Urlcat

Urlbuilder
Java Builders: URL builder
Stars: ✭ 174 (-86.96%)
Mutual labels:  builder, url
Prestashop Clean Urls
Prestashop module. This override module allows to remove IDs from URLs
Stars: ✭ 87 (-93.48%)
Mutual labels:  url
Markdown Builder
1kb Markdown builder for Node.js
Stars: ✭ 67 (-94.98%)
Mutual labels:  builder
Swiftlinkpreview
It makes a preview from an URL, grabbing all the information such as title, relevant texts and images.
Stars: ✭ 1,216 (-8.85%)
Mutual labels:  url
Goscraper
Golang pkg to quickly return a preview of a webpage (title/description/images)
Stars: ✭ 72 (-94.6%)
Mutual labels:  url
Gitio.fish
Create a custom git.io URL.
Stars: ✭ 81 (-93.93%)
Mutual labels:  url
Ngqp
Declaratively synchronize form controls with the URL
Stars: ✭ 65 (-95.13%)
Mutual labels:  url
Tars Cli
CLI for TARS
Stars: ✭ 92 (-93.1%)
Mutual labels:  builder
Libvmod Querystring
Query-string module for Varnish Cache
Stars: ✭ 85 (-93.63%)
Mutual labels:  url
Dartson
Dartson is a Dart library that can be used to convert Dart objects into a JSON string.
Stars: ✭ 78 (-94.15%)
Mutual labels:  builder
Apprater Dialog
A dialog which asks the user to rate the app
Stars: ✭ 77 (-94.23%)
Mutual labels:  builder
React Easy Params
🔗 Auto synchronize your state with the URL and LocalStorage.
Stars: ✭ 73 (-94.53%)
Mutual labels:  url
Djurl
Simple yet helpful library for writing Django urls by an easy, short and intuitive way.
Stars: ✭ 85 (-93.63%)
Mutual labels:  url
Website 2 Apk Builder
Convert your Website to a working Android App. Supports html, php, htm, js, css. Build app from any website or from local directory.
Stars: ✭ 67 (-94.98%)
Mutual labels:  builder
Use Query Params
React Hook for managing state in URL query parameters with easy serialization.
Stars: ✭ 1,278 (-4.2%)
Mutual labels:  url
Url Shortener
Web application that will help you in shortening your url
Stars: ✭ 65 (-95.13%)
Mutual labels:  url
Laravel Multistep Forms
Responsable Multistep Form Builder for Laravel
Stars: ✭ 76 (-94.3%)
Mutual labels:  builder
Laravel Url Shortener
Powerful URL shortening tools in Laravel
Stars: ✭ 80 (-94%)
Mutual labels:  url
Ngx Dynamic Form Builder
FormBuilder + class-transformer + class-validator = dynamic form group builder for Angular10+
Stars: ✭ 93 (-93.03%)
Mutual labels:  builder
Builder
Drag and drop page building using your code components
Stars: ✭ 1,281 (-3.97%)
Mutual labels:  builder


Markdownify
urlcat

Build correct URLs easily.

Build Status npm version minzipped size Coverage Status

What?Why?How?TypeScriptAPIHelpContribute

What?

urlcat is a tiny JavaScript library that makes building URLs very convenient and prevents common mistakes.


Features:

  • Friendly API
  • No dependencies
  • 0.8 KB minified and gzipped
  • TypeScript types provided

Why?

When I call an HTTP API, I usually need to add dynamic parameters to the URL:

const API_URL = 'https://api.example.com/';

function getUserPosts(id, blogId, limit, offset) {
  const requestUrl = `${API_URL}/users/${id}/blogs/${blogId}/posts?limit=${limit}&offset=${offset}`;
  // send HTTP request
}

As you can see, this minimal example is already rather hard to read. It is also incorrect:

  • I forgot that there was a trailing slash at the end of the API_URL constant so this resulted in a URL containing duplicate slashes (https://api.example.com//users).
  • The embedded values need to be escaped using encodeURIComponent

I can use the built-in URL class to prevent duplicate slashes and URLSearchParams to escape the query string. But I still need to escape all path parameters manually.

const API_URL = 'https://api.example.com/';

function getUserPosts(id, blogId, limit, offset) {
  const escapedId = encodeURIComponent(id);
  const escapedBlogId = encodeURIComponent(blogId);
  const path = `/users/${escapedId}/blogs/${escapedBlogId}`;
  const url = new URL(path, API_URL);
  url.search = new URLSearchParams({ limit, offset });
  const requestUrl = url.href;
  // send HTTP request
}

Such a simple task and yet very hard to read and tedious to write! This is where this tiny library can help you:

const API_URL = 'https://api.example.com/';

function getUserPosts(id, limit, offset) {
  const requestUrl = urlcat(API_URL, '/users/:id/posts', { id, limit, offset });
  // send HTTP request
}

The library handles:

  • escaping all parameters
  • concatenating all parts (there will always be exactly one / and ? character between them)

How?

Install

Currently, the package is distributed via npm. (Zip downloads and a CDN are coming soon).

npm install --save urlcat

Usage with Node

Node 10 and above are officially supported. Since the code uses the URL and URLSearchParams classes internally, which aren't available below v10, we cannot support those versions.

To build full URLs (most common use case):

const urlcat = require('urlcat').default;

To use any of the utility functions:

const { query, subst, join } = require('urlcat');

To use all exported functions:

const { default: urlcat, query, subst, join } = require('urlcat');

Usage with TypeScript

TypeScript 2.1 and above are officially supported.

To build full URLs (most common use case):

import urlcat from 'urlcat';

To use any of the utility functions:

import { query, subst, join } from 'urlcat';

To use all exported functions:

import urlcat, { query, subst, join } from 'urlcat';

Usage with Deno

import urlcat from 'https://deno.land/x/urlcat/src/index.ts';

console.log(urlcat('https://api.foo.com', ':name', { id: 25, name: 'knpwrs' }));

TypeScript

This library provides its own type definitions. "It just works", no need to install anything from @types.

API

ParamMap: an object with string keys

type ParamMap = Record<string, any>;

For example, { firstParam: 1, 'second-param': 2 } is a valid ParamMap.

urlcat: build full URLs

function urlcat(baseUrl: string, pathTemplate: string, params: ParamMap): string
function urlcat(baseUrl: string, pathTemplate: string): string
function urlcat(baseTemplate: string, params: ParamMap): string

Examples

  • urlcat('https://api.example.com', '/users/:id/posts', { id: 123, limit: 10, offset: 120 })
    'https://api.example.com/users/123/posts?limit=10&offset=120'
  • urlcat('http://example.com/', '/posts/:title', { title: 'Letters & "Special" Characters' })
    'http://example.com/posts/Letters%20%26%20%22Special%22%20Characters'
  • urlcat('https://api.example.com', '/users')
    'https://api.example.com/users'
  • urlcat('https://api.example.com/', '/users')
    'https://api.example.com/users'
  • urlcat('http://example.com/', '/users/:userId/posts/:postId/comments', { userId: 123, postId: 987, authorId: 456, limit: 10, offset: 120 })
    'http://example.com/users/123/posts/987/comments?authorId=456&limit=10&offset=120'

NOTE about empty path segments: RFC 3986 allows empty path segments in URLs (for example, https://example.com//users////2). urlcat keeps any empty path segments that aren't at the concatenation boundary between baseUrl and pathTemplate. To include an empty path segment there are two options:

  • use a double slash: urlcat('https://example.com/', '//users', { q: 1 })https://example.com//users?q=1
  • use the baseTemplate overload: urlcat('https://example.com//users', { q: 1 })https://example.com//users?q=1

query: build query strings

function query(params: ParamMap): string

Builds a query string using the key-value pairs specified. Keys and values are escaped, then joined by the '&' character.

Examples

params result
{} ''
{ query: 'some text' } 'query=some%20text'
{ id: 42, 'comment-id': 86 } 'id=42&comment-id=86'
{ id: 42, 'a name': 'a value' } 'id=42&a%20name=a%20value'

subst: substitute path parameters

function subst(template: string, params: ParamMap): string

Substitutes parameters with values in a template string. template may contain 0 or more parameter placeholders. Placeholders start with a colon (:), followed by a parameter name that can only contain uppercase or lowercase letters. Any placeholders found in the template are replaced with the value under the corresponding key in params.

Examples

template params result
':id' { id: 42 } '42'
'/users/:id' { id: 42 } '/users/42'
'/users/:id/comments/:commentId' { id: 42, commentId: 86 } '/users/42/comments/86'
'/users/:id' { id: 42, foo: 'bar' } '/users/42'

join: join two strings using exactly one separator

function join(part1: string, separator: string, part2: string): string

Joins the two parts using exactly one separator. If a separator is present at the end of part1 or the beginning of part2, it is removed, then the two parts are joined using separator.

Examples

part1 separator part2 result
'first' ',' 'second' 'first,second'
'first,' ',' 'second'
'first' ',' ',second'
'first,' ',' ',second'

Help

Thank you for using urlcat!

If you need any help using this library, feel free to create a GitHub issue, and ask your questions. I'll try to answer as quickly as possible.

Contribute

Contributions of any kind (pull requests, bug reports, feature requests, documentation, design) are more than welcome! If you like this project and want to help, but feel like you are stuck, feel free to contact the maintainer (Botond Balázs <[email protected]>).

Building from source

Building the project should be quick and easy. If it isn't, it's the maintainer's fault. Please report any problems with building in a GitHub issue.

You need to have a reasonably recent version of node.js to build urlcat. Tested on node version 12.18.3 and npm version 6.14.6.

First, clone the git repository:

git clone [email protected]:balazsbotond/urlcat.git

Then switch to the newly created urlcat directory and install the dependencies:

cd urlcat
npm install

You can then run the unit tests to verify that everything works correctly:

npm test

And finally, build the library:

npm run build

The output will appear in the dist directory.

Happy hacking!

Contributors ✨

All Contributors

Thanks goes to these wonderful people (emoji key):

🚇 🚧 🤔 🤔
Harshil Parmar

💻
📦 📓 🤔 📖 🤔 🚇
🤔 💻
Luyu Cheng

📖

Christian Rackerseder

📖

Aryan Gupta

📖

Jason Kohles

🐛 💻

Tiago Santos Da Silva

💻
🚇
🚇
Sakshi Vattikuti

📖
🤔
David Joseph Guzsik

👀

This project follows the all-contributors specification. Contributions of any kind welcome!

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].