How to simplify the search query parameter?

96 Views Asked by At

The problem

I have a movie database with the indexName: 'movies'.

Let's say my query is John then the domain is domain.tld/?movies[query]=John.

I want to simplify the search query parameter to domain.tld/?keywords=John. How can I do that?

What I already know

After reading through the docs I know that I have to modify the createURL and the parseURL somehow:

  createURL({ qsModule, location, routeState }) {
    const { origin, pathname, hash } = location;
    const indexState = routeState['movies'] || {};
    const queryString = qsModule.stringify(routeState);

    if (!indexState.query) {
      return `${origin}${pathname}${hash}`;
    }

    return `${origin}${pathname}?${queryString}${hash}`;
  },

...

  parseURL({ qsModule, location }) {
    return qsModule.parse(location.search.slice(1));
  },
1

There are 1 best solutions below

0
On

After some try and error here is a solution:

  createURL({ qsModule, location, routeState }) {
    const { origin, pathname, hash } = location;
    const indexState = routeState['movies'] || {}; // routeState[indexName]
    //const queryString = qsModule.stringify(routeState); // default -> movies[query]
    const queryString = 'keywords=' + encodeURIComponent(indexState.query); // NEW

    if (!indexState.query) {
      return `${origin}${pathname}${hash}`;
    }

    return `${origin}${pathname}?${queryString}${hash}`;
  },

...

  parseURL({ qsModule, location }) {
    //return qsModule.parse(location.search.slice(1)); // default: e.g. movies%5Bquery%5D=john
    const query = location.search.match(/=(.*)/g) || []; // NEW
    const queryString = 'movies%5Bquery%5D' + query[0]; // NEW
    return qsModule.parse(queryString); // NEW
  },