0.2.0 • Published 8 months ago

normalize-url-search-params v0.2.0

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

normalize-url-search-params

NPM version NPM monthly download

Normalize a URLSearchParams

Installation

npm install normalize-url-search-params

Available Options

parametertypedefaultdescription
removeEmptybooleantrueRemoves params with an empty string as the value.
removeNullUndefinedbooleantrueRemoves params with null or undefined as the value.
booleanAsNumberbooleantrueForces the boolean value into a number is 0 or 1.
removePage1booleantrueRemoves page param with the value is 1.
sortbooleanfalseSorts all key/value pairs, if any, by their keys.
dataObject{}A record of string keys and any values.
removeParametersArray<string\|RegExp>[/^utm_\w+/i]Removes params that matches any of the provided strings or regexes.

Example:

test('simple', () => {
  expect(
    normalizeUrlSearchParams('/admin/posts', {
      data: {
        page: 2,
        sort: 'created_at',
      },
    })
  ).toEqual('/admin/posts?page=2&sort=created_at');
});

test('test with removeEmpty', () => {
  expect(
    normalizeUrlSearchParams('/admin/posts?abc', {
      data: {
        xyz: '',
      },
      removeEmpty: true,
    })
  ).toEqual('/admin/posts');
});

test('test with booleanAsNumber', () => {
  expect(
    normalizeUrlSearchParams('/admin/posts?active=true', {
      data: {
        admin: false,
      },
      booleanAsNumber: true,
    })
  ).toEqual('/admin/posts?active=1&admin=0');
});

test('test with removePage1', () => {
  expect(
    normalizeUrlSearchParams('/admin/posts?page=1', {
      data: {
        active: true,
        role: 'admin',
      },
      removePage1: true,
    })
  ).toEqual('/admin/posts?active=1&role=admin');
});

test('test with sort', () => {
  expect(
    normalizeUrlSearchParams('/admin/posts?page=2&active=true', {
      data: {
        active: false,
      },
      sort: true,
    })
  ).toEqual('/admin/posts?active=0&page=2');
});

test('test with removeParameters', () => {
  expect(
    normalizeUrlSearchParams('/admin/posts?page=2&sort=created_at&ref=123', {
      removeParameters: ['ref'],
    })
  ).toEqual('/admin/posts?page=2&sort=created_at');
});

test('test with full url', () => {
  expect(
    normalizeUrlSearchParams('http://domain.com/admin/posts?page=2', {
      data: {
        admin: true,
      },
    })
  ).toEqual('http://domain.com/admin/posts?page=2&admin=1');
});

License

MIT

0.2.0

8 months ago

0.1.3

2 years ago

0.1.2

2 years ago

0.1.1

2 years ago

0.1.0

2 years ago