Files
redash/client/app/services/parameters/QueryBasedDropdownParameter.js
Gabriel Dutra 9f7844640a Introduce inheritance to the Parameter structure (#4049)
* Start draft for new Parameter structure

* Add the rest of the methods

* EnumParameter

* QueryBasedDropdownParameter

* DateParameter

* DateRangeParameter

* Update Parameter usage on code

* Merge dynamicValue into normalizedValue

* Add updateLocals and omit unwanted props

* Allow null NumberParameter and omit parentQueryId

* Rename parameter getValue to getExecutionValue

* Update $$value to normalizedValue + omit on save

* Add a few comments

* Remove ngModel property from Parameter

* Use value directly in DateRangeParameter

* Use simpler separator for DateRange url param

* Add backward compatibility

* Use normalizeValue null value for isEmpty

* Start creating jest tests

* Add more tests

* Normalize null value for multi mode in Enum

* Use saved value for param isEmpty
2019-10-24 12:42:30 +03:00

78 lines
2.2 KiB
JavaScript

import { isNull, isUndefined, isArray, isEmpty, get, map, join, has } from 'lodash';
import { Query } from '@/services/query';
import { Parameter } from '.';
class QueryBasedDropdownParameter extends Parameter {
constructor(parameter, parentQueryId) {
super(parameter, parentQueryId);
this.queryId = parameter.queryId;
this.multiValuesOptions = parameter.multiValuesOptions;
this.setValue(parameter.value);
}
normalizeValue(value) {
if (isUndefined(value) || isNull(value) || (isArray(value) && isEmpty(value))) {
return null;
}
if (this.multiValuesOptions) {
value = isArray(value) ? value : [value];
} else {
value = isArray(value) ? value[0] : value;
}
return value;
}
getExecutionValue(extra = {}) {
const { joinListValues } = extra;
if (joinListValues && isArray(this.value)) {
const separator = get(this.multiValuesOptions, 'separator', ',');
const prefix = get(this.multiValuesOptions, 'prefix', '');
const suffix = get(this.multiValuesOptions, 'suffix', '');
const parameterValues = map(this.value, v => `${prefix}${v}${suffix}`);
return join(parameterValues, separator);
}
return this.value;
}
toUrlParams() {
const prefix = this.urlPrefix;
let urlParam = this.value;
if (this.multiValuesOptions && isArray(this.value)) {
urlParam = JSON.stringify(this.value);
}
return {
[`${prefix}${this.name}`]: !this.isEmpty ? urlParam : null,
};
}
fromUrlParams(query) {
const prefix = this.urlPrefix;
const key = `${prefix}${this.name}`;
if (has(query, key)) {
if (this.multiValuesOptions) {
try {
const valueFromJson = JSON.parse(query[key]);
this.setValue(isArray(valueFromJson) ? valueFromJson : query[key]);
} catch (e) {
this.setValue(query[key]);
}
} else {
this.setValue(query[key]);
}
}
}
loadDropdownValues() {
if (this.parentQueryId) {
return Query.associatedDropdown({ queryId: this.parentQueryId, dropdownQueryId: this.queryId }).$promise;
}
return Query.asDropdown({ id: this.queryId }).$promise;
}
}
export default QueryBasedDropdownParameter;