Miss any of our Open RFC calls?Watch the recordings here! »

psr7-js

0.1.2 • Public • Published

Latest Stable Version License Build Status Coverage Status Total Downloads

PSR7-JS

URI

Coming from the PHP World, you probably use PSR-7 UriInterface almost every day to manipulate URIs.

But what if you come to front-end development? You can use native URL objects, which are mutable, have no fluent setters and different property names. And only absolute URLs are supported.

So, this library is intended to expose the same methods as PSR-7, in an immutable way:

import {URI} from 'psr7-js';
 
let uri = new URI('/foo'); // Relative URLs are supported - Defaults to window.location.href
uri = uri.withQuery('foo=bar');
 
console.log(uri.toString()); // /foo?foo=bar

QueryString

Query Strings aren't part of the PSR-7 specification, but there are still issues when dealing with complex query strings in Javascript.

There are lots of query string manipulation libraries on NPM packages, but I couldn't find one which properly handles PHP's array syntax (sequential and/or associative).

import {QueryString} from 'psr7-js';
 
let qs = new QueryString('?foo=bar'); // Accepts strings (leading ? is ignored) or objects - Defaults to window.location.search
qs = qs.withParam('bar', 'baz'); // foo=bar&bar=baz
qs = qs.withoutParam('bar'); // foo=bar
qs = qs.withParam('foos', ['foo', 'bar']); // foo=bar&foos[]=foo&foos[]=bar
qs = qs.withParam('sort', {'updated_at': 'desc', 'hits': 'desc'}); // foo=bar&foos[]=foo&foos[]=bar&sort[updated_at]=desc&hits=desc
qs = qs.withoutParam('sort', 'hits'); // foo=bar&foos[]=foo&foos[]=bar&sort[updated_at]=desc
 
console.log(qs.getParams());
 
/*
{
  "foo": "bar",
  "foos": [
    "foo",
    "bar"
  ],
  "sort": {
    "updated_at": "desc"
  }
}
 */
 
console.log(qs.toString()); // foo=bar&foos[]=foo&foos[]=bar&sort[updated_at]=desc

Inspired by bentools/querystring.

Additionnal notes

This library is intended to be used with a bundler like Webpack.

If you prefer, you can still have URI and QueryString registered in your global scope (which is not adviced) by using dist/uri.min.js and dist/query-string.min.js into <script> tags.

Tests

yarn test // or npm run-script test

License

MIT.

Install

npm i psr7-js

DownloadsWeekly Downloads

4

Version

0.1.2

License

MIT

Unpacked Size

59.2 kB

Total Files

26

Last publish

Collaborators

  • avatar