hyper-express icon indicating copy to clipboard operation
hyper-express copied to clipboard

add query setter

Open fawzy0z opened this issue 11 months ago • 1 comments

Hello,

I’ve been working on a validation middleware to sanitize query parameters. My specific use case involved normalizing an email query parameter (e.g., trimming spaces and converting it to lowercase) so that the sanitized value could be used consistently in subsequent middleware or route handlers.

During implementation, I encountered the following errors when attempting to set a new value for the query property:

  • TypeError: Cannot set property query of #<Request> which has only a getter.
  • TypeError: Cannot set property query_parameters of #<Request> which has only a getter.

Solution

I’ve identified the cause and resolved the issue. My approach ensures the query parameters are sanitized without conflicting with the Request object’s read-only properties. This solution should help anyone facing a similar problem.

Looking forward to your feedback!

Thank you.

fawzy0z avatar Jan 01 '25 21:01 fawzy0z

You can overwrite the request object so that query returns a custom value.

This was my solution:

 Object.defineProperty(req, "query", {
    get() {
      return parse(this.path_query, options);
    },
  });

Also, for global use, you can create a middleware:

const customQueryParseMiddleware:MiddlewareHandler = (req, res, next) => {
   Object.defineProperty(req, "query", {
      get() {
        return parse(this.path_query, options);
      },
    });
}


zenozaga avatar Jan 10 '25 22:01 zenozaga