Skip to content

Added variables to data query #1470

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Jan 29, 2025
13 changes: 9 additions & 4 deletions client/packages/lowcoder-design/src/components/keyValueList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -76,20 +76,25 @@ export const KeyValueList = (props: {
list: ReactNode[];
onAdd: () => void;
onDelete: (item: ReactNode, index: number) => void;
isStatic?: boolean;
}) => (
<>
{props.list.map((item, index) => (
<KeyValueListItem key={index /* FIXME: find a proper key instead of `index` */}>
{item}
<DelIcon
onClick={() => props.list.length > 1 && props.onDelete(item, index)}
$forbidden={props.list.length === 1}
/>
{!props.isStatic &&
<DelIcon
onClick={() => props.list.length > 1 && props.onDelete(item, index)}
$forbidden={props.list.length === 1}
/>
}
</KeyValueListItem>
))}
{!props.isStatic &&
<AddBtn onClick={props.onAdd}>
<AddIcon />
{trans("addItem")}
</AddBtn>
}
</>
);
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,100 @@ import { BranchDiv, Dropdown } from "lowcoder-design";
import { BottomResTypeEnum } from "types/bottomRes";
import { getPromiseAfterDispatch } from "util/promiseUtils";
import { trans } from "i18n";
import {keyValueListControl, keyValueListToSearchStr, withDefault} from "lowcoder-sdk";
import {KeyValue} from "@lowcoder-ee/types/common";
import { useCallback, useContext, useEffect, useMemo } from "react";

const ExecuteQueryPropertyView = ({
comp,
placement,
}: {
comp: any,
placement?: "query" | "table"
}) => {
const getQueryOptions = useCallback((editorState?: EditorState) => {
const options: { label: string; value: string; variable?: Record<string, string> }[] =
editorState
?.queryCompInfoList()
.map((info) => {
return {
label: info.name,
value: info.name,
variable: info.data.variable,
}
})
.filter(
// Filter out the current query under query
(option) => {
if (
placement === "query" &&
editorState.selectedBottomResType === BottomResTypeEnum.Query
) {
return option.value !== editorState.selectedBottomResName;
}
return true;
}
) || [];

// input queries
editorState
?.getModuleLayoutComp()
?.getInputs()
.forEach((i) => {
const { name, type } = i.getView();
if (type === InputTypeEnum.Query) {
options.push({ label: name, value: name });
}
});
return options;
}, [placement]);

const getVariableOptions = useCallback((editorState?: EditorState) => {
return comp.children.queryVariables.propertyView({
label: trans("eventHandler.queryVariables"),
layout: "vertical",
isStatic: true,
keyFixed: true,
});
}, [comp.children.queryVariables.getView()])

return (
<>
<BranchDiv $type={"inline"}>
<EditorContext.Consumer>
{(editorState) => (
<>
<Dropdown
showSearch={true}
value={comp.children.queryName.getView()}
options={getQueryOptions(editorState)}
label={trans("eventHandler.selectQuery")}
onChange={(value) => {
const options = getQueryOptions(editorState);
const selectedQuery = options.find(option => option.value === value);
const variables = selectedQuery ? Object.keys(selectedQuery.variable || {}) : [];
comp.dispatchChangeValueAction({
queryName: value,
queryVariables: variables.map((variable) => ({key: variable, value: ''})),
});
}}
/>
</>
)}
</EditorContext.Consumer>
</BranchDiv>
<BranchDiv>
<EditorContext.Consumer>
{(editorState) => getVariableOptions(editorState)}
</EditorContext.Consumer>
</BranchDiv>
</>
);
}
const ExecuteQueryTmpAction = (function () {
const childrenMap = {
queryName: SimpleNameComp,
queryVariables: withDefault(keyValueListControl(false, [], "string"), [])
};
return new MultiCompBuilder(childrenMap, () => {
return () => Promise.resolve(undefined as unknown);
Expand All @@ -22,6 +112,15 @@ const ExecuteQueryTmpAction = (function () {
export class ExecuteQueryAction extends ExecuteQueryTmpAction {
override getView() {
const queryName = this.children.queryName.getView();
// const queryParams = keyValueListToSearchStr(Array.isArray(this?.children?.query) ? (this.children.query as unknown as any[]).map((i: any) => i.getView() as KeyValue) : []);
const result = Object.values(this.children.queryVariables.children as Record<string, {
children: {
key: { unevaledValue: string },
value: { unevaledValue: string }
}}>)
.filter(item => item.children.key.unevaledValue !== "" && item.children.value.unevaledValue !== "")
.map(item => ({[item.children.key.unevaledValue]: item.children.value.unevaledValue}))
.reduce((acc, curr) => Object.assign(acc, curr), {});
if (!queryName) {
return () => Promise.resolve();
}
Expand All @@ -30,9 +129,7 @@ export class ExecuteQueryAction extends ExecuteQueryTmpAction {
this.dispatch,
routeByNameAction(
queryName,
executeQueryAction({
// can add context in the future
})
executeQueryAction({args: result})
),
{ notHandledError: trans("eventHandler.notHandledError") }
);
Expand All @@ -46,55 +143,11 @@ export class ExecuteQueryAction extends ExecuteQueryTmpAction {
}

propertyView({ placement }: { placement?: "query" | "table" }) {
const getQueryOptions = (editorState?: EditorState) => {
const options: { label: string; value: string }[] =
editorState
?.queryCompInfoList()
.map((info) => ({
label: info.name,
value: info.name,
}))
.filter(
// Filter out the current query under query
(option) => {
if (
placement === "query" &&
editorState.selectedBottomResType === BottomResTypeEnum.Query
) {
return option.value !== editorState.selectedBottomResName;
}
return true;
}
) || [];

// input queries
editorState
?.getModuleLayoutComp()
?.getInputs()
.forEach((i) => {
const { name, type } = i.getView();
if (type === InputTypeEnum.Query) {
options.push({ label: name, value: name });
}
});
return options;
};
return (
<BranchDiv $type={"inline"}>
<EditorContext.Consumer>
{(editorState) => (
<>
<Dropdown
showSearch={true}
value={this.children.queryName.getView()}
options={getQueryOptions(editorState)}
label={trans("eventHandler.selectQuery")}
onChange={(value) => this.dispatchChangeValueAction({ queryName: value })}
/>
</>
)}
</EditorContext.Consumer>
</BranchDiv>
);
<ExecuteQueryPropertyView
comp={this}
placement={placement}
/>
)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ const childrenMap = {
};

export const GoToURLAction = new MultiCompBuilder(childrenMap, (props) => {
return () => {
return () => {
const queryParams = keyValueListToSearchStr(
props.query.map((i) => i.getView() as KeyValue)
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -167,12 +167,18 @@ const EventHandlerControlPropertyView = (props: {
if (eventConfigs.length === 0) {
return;
}

const queryVariables = editorState
?.selectedOrFirstQueryComp()
?.children.variables.children.variables.toJsonValue();

const queryExecHandler = {
compType: "executeQuery",
comp: {
queryName: editorState
?.selectedOrFirstQueryComp()
?.children.name.getView(),
queryVariables: queryVariables?.map((variable) => ({...variable, value: ''})),
},
};
const messageHandler = {
Expand Down
27 changes: 17 additions & 10 deletions client/packages/lowcoder/src/comps/controls/keyValueControl.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ export type KeyValueControlParams = ControlParams & {
typeTooltip?: ReactNode;
keyFlexBasics?: number;
valueFlexBasics?: number;
isStatic?: boolean;
keyFixed?: boolean;
};

/**
Expand Down Expand Up @@ -82,16 +84,20 @@ function keyValueControl<T extends OptionsType>(
return (
<KeyValueWrapper>
<KeyWrapper $flexBasics={params.keyFlexBasics}>
{this.children.key.propertyView({ placeholder: "key", indentWithTab: false })}
{hasType && params.showType && (
<TypeWrapper>
{this.children.type.propertyView({
placeholder: "key",
indentWithTab: false,
tooltip: params.typeTooltip,
})}
</TypeWrapper>
)}
{params.keyFixed?
<>{this.children.key.getView()}</>
:<>
{this.children.key.propertyView({ placeholder: "key", indentWithTab: false })}
{hasType && params.showType && (
<TypeWrapper>
{this.children.type.propertyView({
placeholder: "key",
indentWithTab: false,
tooltip: params.typeTooltip,
})}
</TypeWrapper>
)}
</>}
</KeyWrapper>
<ValueWrapper $flexBasics={params.valueFlexBasics}>
{this.children.value.propertyView({
Expand Down Expand Up @@ -136,6 +142,7 @@ export function keyValueListControl<T extends OptionsType>(
list={this.getView().map((child) => child.propertyView(params))}
onAdd={() => this.dispatch(this.pushAction({}))}
onDelete={(item, index) => this.dispatch(this.deleteAction(index))}
isStatic={params.isStatic}
/>
</ControlPropertyViewWrapper>
);
Expand Down
29 changes: 28 additions & 1 deletion client/packages/lowcoder/src/comps/queries/queryComp.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -67,14 +67,15 @@ import { JSONObject, JSONValue } from "../../util/jsonTypes";
import { BoolPureControl } from "../controls/boolControl";
import { millisecondsControl } from "../controls/millisecondControl";
import { paramsMillisecondsControl } from "../controls/paramsControl";
import { NameConfig, withExposingConfigs } from "../generators/withExposing";
import { DepsConfig, NameConfig, withExposingConfigs } from "../generators/withExposing";
import { HttpQuery } from "./httpQuery/httpQuery";
import { StreamQuery } from "./httpQuery/streamQuery";
import { QueryConfirmationModal } from "./queryComp/queryConfirmationModal";
import { QueryNotificationControl } from "./queryComp/queryNotificationControl";
import { QueryPropertyView } from "./queryComp/queryPropertyView";
import { getTriggerType, onlyManualTrigger } from "./queryCompUtils";
import { messageInstance } from "lowcoder-design/src/components/GlobalInstances";
import {VariablesComp} from "@lowcoder-ee/comps/queries/queryComp/variablesComp";

const latestExecution: Record<string, string> = {};

Expand Down Expand Up @@ -153,6 +154,7 @@ const childrenMap = {
defaultValue: 10 * 1000,
}),
confirmationModal: QueryConfirmationModal,
variables: VariablesComp,
periodic: BoolPureControl,
periodicTime: millisecondsControl({
defaultValue: Number.NaN,
Expand Down Expand Up @@ -361,6 +363,8 @@ QueryCompTmp = class extends QueryCompTmp {
}
if (action.type === CompActionTypes.EXECUTE_QUERY) {
if (getReduceContext().disableUpdateState) return this;
if(!action.args) action.args = this.children.variables.children.variables.toJsonValue().reduce((acc, curr) => Object.assign(acc, {[curr.key as string]:curr.value}), {});

return this.executeQuery(action);
}
if (action.type === CompActionTypes.CHANGE_VALUE) {
Expand Down Expand Up @@ -404,16 +408,21 @@ QueryCompTmp = class extends QueryCompTmp {
return this;
}




/**
* Process the execution result
*/
private processResult(result: QueryResult, action: ExecuteQueryAction, startTime: number) {
const lastQueryStartTime = this.children.lastQueryStartTime.getView();

if (lastQueryStartTime > startTime) {
// There are more new requests, ignore this result
// FIXME: cancel this request in advance in the future
return;
}

const changeAction = multiChangeAction({
code: this.children.code.changeValueAction(result.code ?? QUERY_EXECUTION_OK),
success: this.children.success.changeValueAction(result.success ?? true),
Expand Down Expand Up @@ -470,6 +479,7 @@ QueryCompTmp = class extends QueryCompTmp {
applicationId: applicationId,
applicationPath: parentApplicationPath,
args: action.args,
variables: action.args,
timeout: this.children.timeout,
callback: (result) => this.processResult(result, action, startTime)
});
Expand Down Expand Up @@ -653,6 +663,23 @@ export const QueryComp = withExposingConfigs(QueryCompTmp, [
new NameConfig("isFetching", trans("query.isFetchingExportDesc")),
new NameConfig("runTime", trans("query.runTimeExportDesc")),
new NameConfig("latestEndTime", trans("query.latestEndTimeExportDesc")),
new DepsConfig(
"variable",
(children: any) => {
return {data: children.variables.children.variables.node()};
},
(input) => {
if (!input.data) {
return undefined;
}
const newNode = Object.values(input.data)
.filter((kvNode: any) => kvNode.key.text.value)
.map((kvNode: any) => ({[kvNode.key.text.value]: kvNode.value.text.value}))
.reduce((prev, obj) => ({...prev, ...obj}), {});
return newNode;
},
trans("query.variables")
),
new NameConfig("triggerType", trans("query.triggerTypeExportDesc")),
]);

Expand Down
Loading
Loading