Aron
Aron

Reputation: 412

Ember dynamic query parameters

I have what I believe to be common but complicated problem to model. I've got a product configurator that has a series of buttons. Every time the user clicks on a button (corresponding to a change in the product configuration), the url will change, essentially creating a bookmarkable state to that configuration. The big caveat: I do not get to know what configuration options or values are until after app initialization.

I'm modeling this using EmberCLI. After much research, I don't think it's a wise idea to try to fold these directly into the path component, and I'm looking into using the new Ember query string additions. That should work for allowing bookmarkability, but I still have the problem of not knowing what those query parameters are until after initialization.

What I need is a way to allow my Ember app to query the server initially for a list of parameters it should accept. On the link above, the documentation uses the parameter 'filteredArticles' for a computed property. Within the associated function, they've hard-coded the value that the computed property should filter by. Is it a good idea to try to extend this somehow to be generalizable, with arguments? Can I even add query parameters on the fly? I was hoping for an assessment of the validity of this approach before I get stuck down the rabbit hole with it.

Upvotes: 0

Views: 1112

Answers (1)

Stephen Prockow
Stephen Prockow

Reputation: 199

I dealt with a similar issue when generating a preview popup of a user's changes. The previewed model had a dynamic set of properties that could not be predetermined. The solution I came up with was to base64 encode a set of data and use that as the query param.

Your url would have something like this ?filter=ICLkvaDlpb0iLAogICJtc2dfa3

The query param is bound to a 2-way computed that takes in a base64 string and outputs a json obj,

JSON.parse(atob(serializedPreview));

as well as doing the reverse: take in a json obj and output a base64 string.

serializedPreview = btoa(JSON.stringify(filterParams));

You'll need some logic to prevent empty json objects from being serialized. In that case, you should just set the query param as null, and remove it from your url.

Using this pattern, you can store just about anything you want in your query params and still have the url as shareable. However, the downside is that your url's query params are obfuscated from your users, but I imagine that most users don't really read/edit query params by hand.

Upvotes: 3

Related Questions