reduxjs/redux-toolkit

feat req: URL building helpers for RTK query?

SEAPUNK opened this issue · 4 comments

As I was reading RTK query's example, it didn't sit right with me that the user is expected to do plain string interpolation of variables into the query URL:

{
// [...]
    getPost: builder.query({
      query: postId => `/posts/${postId}` // what if postId is "foo/bar"?
    })
// [...]
}

Since we have things like tagged template literals, would it make sense to add a small utility to safely interpolate variables into URI paths and include it as a best practice? Kind of like how uri-tag does it:

// instead of this
(postId) => `/posts/${postId}` // "/posts/foo/bar"

// something like this?
import {uri} from '@redux/toolkit/query';
(postId) => uri`/posts/${postId}` // "/posts/foo%2Fbar"

especially since params are automatically serialized with paramsSerializer

I can see the suggestion, but I think that's really out of scope for RTK as a library. I would assume there have to be similar standalone libraries on NPM that could be used for this.

(FWIW, our examples are just that, "examples" - we can only show off so many concepts and ideas in our docs, and users are always welcome to expand on those or customize them for their own use cases.)

What was the motivation behind paramsSerializer, then? By that logic, the user could construct the path with the query params themselves, too. I feel that if RTK's entire purpose is to exemplify best practices, I'd expect it to be holistic in that sense, especially for less experienced developers. A bit whatstheword, but I see this similar to how SQL-related stuff tends to have its examples steer the user to avoiding SQL injections by default.

// what if postId is "foo/bar"?

In a lot of cases, perfectly fine - I'm pretty sure a lot of our users use it for that exact purpose. Only a minority of these variables are user-provided.

What was the motivation behind paramsSerializer, then?

It's an escape hatch to be able to plug in a third-party library into the existing logic, in case you want more than the "standard" URLSearchParams.

Pretty much what we told you here - we offer some barebones tools, but we want to keep our fetchBaseQuery around 1kB, and not blow it up to an axios size of 10kB or so.

We try to fulfill a "90% users" use case with Redux Toolkit, we don't optimize for coverage of every last use case at the cost of bundle size for all of our users - and you are the first person in three years that brought this up.

There are already good libraries for this out there, and there is also a place to plug them in, so we don't need to create a new escape hatch.

Fair enough. Thanks for the replies.