offirgolan / ember-parachute

Improved Query Params for Ember
https://offirgolan.github.io/ember-parachute
MIT License
199 stars 40 forks source link

Dynamically set query params #54

Open allthesignals opened 6 years ago

allthesignals commented 6 years ago

I would like to be able to define some query parameters dynamically. My first approach is to do this from the Route in setupController:

  setupController(controller, model) {
    // Parachute things here, dynamically build QP configuration object

    const parachuteController = controller.reopen(ParachuteParams.Mixin);
    super.setupController(parachuteController, model);
  }

This does not work because the query params don't seem to be set or updated when the properties are changed on the controller.

I've researched this quite a bit, but I can't find any different approach other than this discussion.

Any thoughts appreciated, thanks

cmackenz commented 6 years ago

@allthesignals, just ran into this issue myself. Have you found a solution/workaround, yet?

cmackenz commented 6 years ago

Not sure if it works for you but I ended doing something like this:

 // metadata query param is in this format: ?metadata=foo,123|bar,abc
  metadata: {
    defaultValue: [],
    refresh: true,
    serialize(value) {
      return value.map(v => `${v.key},${v.value}`).join('|');
    },
    deserialize(value = '') {
      let pairs = value.split('|') || [];

      return pairs.map(meta => {
        let [key, value] = meta.split(',');
        return { key, value };
      });
    }
  },
allthesignals commented 6 years ago

I did something similar but wanted something more standard-looking. I’m still working on it, you can see a discussion about it here: https://discuss.emberjs.com/t/setting-query-params-programmatically/14665

I have the additional step of needing to alias QP’d props to models, and having those update.

velrest commented 6 years ago

on a side note; is it possible to dynamically set the as attribute since i use my component for multiple models and they have different QP names.

velrest commented 6 years ago

I actually found somewhat of a solution for my problem:

const QueryParams = new QueryParams(
  {
    inFilter: {
      defaultValue: null,
      refresh: true
    },
    notInFilter: {
      defaultValue: null,
      refresh: true
    }
  },
  true
);

export default Component.extend(QueryParams.Mixin, {
  init() {
    // Set `as` dynamically based on component attributes
    set(QueryParams, "queryParams.inFilter.as", this["filter-field"]);
    set(QueryParams, "queryParams.notInFilter.as", `not_in_${this["filter-field"]}`);
    //...
  }
});

I looked into the source code and the query-params are computed based off the original object which the mixin is generated from. So if we reset as on the qp's on the original object the mixin also has the new attributes.