2.1.7 • Published 8 months ago

@smart-gate/query-params v2.1.7

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

@smart-gate/query-params

A lightweight, framework-agnostic package designed to help manage query parameters for filters, pagination, and other browser state data. Seamlessly preserve complex data structures in your browser's path queries, enhancing user experience (UX) by maintaining their preferences even as they navigate back and forth.

Why Use This Package?

Managing query parameters can be challenging, especially with complex data structures. @smart-gate/query-params simplifies this process with an easy-to-use API that works across frameworks. It offers a structured way to persist user preferences and selections in the browser, providing a smoother user experience.

Key Benefits

  • Simplifies Query Management: Handle even the most complex data structures effortlessly.
  • Framework-Agnostic: Compatible with any JavaScript framework or library.
  • Enhances User Experience: Preserves user preferences and inputs.

Installation

Install the package via npm:

npm install @smart-gate/query-params

Sample Transformation

With @smart-gate/query-params, transforming and managing complex objects in the browser's query string is straightforward. The setQueryParams(objectToPreserve) function enables easy setup.

Example Input Object:

const userPreferences = {
	name: 'John',
	age: 17,
	alive: true,
	location: {
		planet: 'Earth'
	},
	hobbies: ['football', 'swimming', 'sky-diving', ['soccer'], { canWork: false, prefersToDie: true }],
	emotions: [
		{ state: 'anger', cause: 'threat' },
		{ state: 'disgust', cause: 'life' }
	]
};

Transformed Query Object:

const queryParams = {
	name: 'John',
	'age()': 17,
	'alive!!': true,
	'location.planet': 'Earth',
	'hobbies[0]': 'football',
	'hobbies[1]': 'swimming',
	'hobbies[2]': 'sky-diving',
	'hobbies[3][0]': 'soccer',
	'hobbies[4].canWork!!': false,
	'hobbies[4].prefersToDie!!': true,
	'emotions[0].state': 'anger',
	'emotions[0].cause': 'threat',
	'emotions[1].state': 'disgust',
	'emotions[1].cause': 'life'
};

Using this structure, you can save complex objects to the browser’s query string without limitations and retrieve the original object with getQueryParams().

Usage

@smart-gate/query-params is versatile and works with any framework. Here’s an example of how to use it in a Vue.js component.

Vue Example Component

Below is a Vue.js component that demonstrates how to use @smart-gate/query-params to manage filter data in the browser's query string.

<template>
	<div class="filter-container">
		<p class="filter-title">Filter Information</p>
		<div class="input-group">
			<input v-model="filter.firstName" placeholder="First Name" />
			<input v-model="filter.lastName" placeholder="Last Name" />
			<input v-model="filter.age" placeholder="Age" type="number" />
		</div>
	</div>
</template>

<script setup>
import { onMounted, ref, watch } from 'vue';
import { getQueryParams, setQueryParams } from '@smart-gate/query-params';

const filter = ref({
	firstName: 'default value',
	lastName: null,
	age: null
});

onMounted(() => {
	filter.value = Object.assign(filter.value, { ...getQueryParams() });
});

watch(filter.value, newVal => {
	setQueryParams(newVal);
});
</script>

<style scoped>
.filter-container {
	padding: 20px;
	font-family: Arial, sans-serif;
}

.filter-title {
	font-weight: bold;
	font-size: 18px;
	margin-bottom: 10px;
}

.input-group {
	display: flex;
	gap: 10px;
	margin-bottom: 10px;
}

input {
	padding: 8px;
	border-radius: 5px;
	border: 1px solid #ccc;
}

input[type='number'] {
	width: 80px;
}
</style>

or you can simply use setQueryParamsByKey and getQueryParamsByKey function to update individual properties.

API Reference

@smart-gate/query-params provides a set of utility functions to serialize and deserialize complex objects for use in query parameters. Below are the core functions available in this package:

getQueryParams()

  • Description: Retrieves all query parameters from the current URL as a deserialized object. This is useful when you need to load stored user preferences or filter criteria on page load.
  • Returns: {object} - An object representing the URL's query parameters, with nested structures restored if applicable.

    Example:

    const params = getQueryParams();
    console.log(params);
    // Output: { name: 'John', age: 17, location: { planet: 'Earth' }, ... }

setQueryParams(data)

  • Description: Serializes an object and updates the browser's URL with the resulting query string. This allows you to save complex data in the URL for persistence.
  • Parameters: data - {object} The object to be serialized and added to the query parameters.
  • Returns: void

    Example:

    const userPreferences = { name: 'John', age: 17, location: { planet: 'Earth' } };
    setQueryParams(userPreferences);
    // URL is updated with ?name=John&age=17&location.planet=Earth

getQueryParamsByKey(property)

  • Description: Retrieves a single query parameter value based on a provided key. If the key refers to a nested structure, this function will locate and return the specific nested value.
  • Parameters: property - {string} The name of the query parameter to retrieve.
  • Returns: unknown - The value associated with the specified query parameter.

    Example:

    const age = getQueryParamsByKey('age');
    console.log(age);
    // Output: 17

setQueryParamsByKey(key, value)

  • Description: Updates a specific query parameter in the current URL without affecting others. Useful for updating a single property in the query string.
  • Parameters:
    • key - {string} The name of the query parameter to set.
    • value - {unknown} The value to associate with the key.
  • Returns: void

    Example:

    setQueryParamsByKey('hobbies[0]', 'football');
    // URL is updated with ?hobbies[0]=football
  • removeQueryParams()

  • Description: Clears all queries parameter in the current URL. Useful for resetting your filter or pagination etc.

  • Returns: void

    Example:

    setQueryParamsByKey('hobbies[0]', 'football');
    // URL is updated with ?hobbies[0]=football

serializeObjectKey(deserialized)

  • Description: Converts a nested object into a flat object with keys representing the path to each value, suitable for use as query parameters.
  • Parameters: deserialized - {object} The nested object to serialize.
  • Returns: {object} - The flattened object with path-based keys.

    Example:

    const data = { user: { name: 'Alice', age: 30 } };
    const serialized = serializeObjectKey(data);
    console.log(serialized);
    // Output: { 'user.name': 'Alice', 'user.age': 30 }

deserializeObjectKey(serialized)

  • Description: Reconstructs a flat object with path-based keys into a nested object.
  • Parameters: serialized - {object} The flattened object to unserialize.
  • Returns: {object} - The nested object.

    Example:

    const serialized = { 'user.name': 'Alice', 'user.age': 30 };
    const data = deserializeObjectKey(serialized);
    console.log(data);
    // Output: { user: { name: 'Alice', age: 30 } }