|
| 1 | +# JavaScript query |
| 2 | + |
| 3 | +There are cases where you want to orchestrate operations, for instance, after triggering two queries, you want to combine and store their results to a temporary state, and then open a modal. This process can be complicated when chaining several event handlers, and certainly cannot be done in one line of code in `{{ }}`. That's where JavaScript (JS) query comes into play. It unleashes the ability to interact with components and queries by writing complex JS queries to achieve the following operations: |
| 4 | + |
| 5 | +* Interact with UI components |
| 6 | +* Trigger queries |
| 7 | +* Access third-party JS libraries |
| 8 | +* Customize functions |
| 9 | + |
| 10 | +The following example is for you to quickly understand what JS query is and how it works. |
| 11 | + |
| 12 | +## Use JS query to join query results |
| 13 | + |
| 14 | +SQL query `query1` reads `id`, `first_name`, `last_name` and `tid` fields from table `players` in a PostgreSQL database. |
| 15 | + |
| 16 | +```sql |
| 17 | +select id, first_name, last_name, tid from users |
| 18 | +``` |
| 19 | + |
| 20 | +SQL query `query2` reads `tid`, `city` and `name` fields from table `teams` in a PostgreSQL database. |
| 21 | + |
| 22 | +```sql |
| 23 | +select tid, city, name from teams |
| 24 | +``` |
| 25 | + |
| 26 | +Use a JS query to left join `query1` and `query2` on the same `tid` in the following steps. |
| 27 | + |
| 28 | +1. Create `query3`, and choose **Run** **JavaScript Code**. |
| 29 | + |
| 30 | + |
| 31 | + |
| 32 | + <figure><img src="../../.gitbook/assets/js-query-1.PNG" alt=""><figcaption></figcaption></figure> |
| 33 | +2. Insert the following code. |
| 34 | + |
| 35 | + ```javascript |
| 36 | + return Promise.all([query1.run(), query2.run()]).then( |
| 37 | + data => join(data[0], data[1]), |
| 38 | + error => {} |
| 39 | + ); |
| 40 | + |
| 41 | + function join(players, teams) { |
| 42 | + return players.map(player => { |
| 43 | + const team = teams.find(t => player.tid === t.tid); |
| 44 | + return { ...player, ...team }; |
| 45 | + }); |
| 46 | + } |
| 47 | + ``` |
| 48 | + |
| 49 | + \ |
| 50 | + In this code snippet, the `Promise.all()` method receives the results of `query1` and `query2`, and the `join()` method joins their results after a successful run based on the values of `tid` field.\ |
| 51 | + |
| 52 | + |
| 53 | + <figure><img src="../../.gitbook/assets/js-query-2.PNG" alt=""><figcaption></figcaption></figure> |
| 54 | + |
| 55 | +## How to use JS query |
| 56 | + |
| 57 | +### Return data |
| 58 | + |
| 59 | +Use `return` syntax to return result. For example, the following code returns `3`. |
| 60 | + |
| 61 | +```javascript |
| 62 | +return Math.floor(3.4) |
| 63 | +``` |
| 64 | + |
| 65 | +The result returned can also be a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/Promise) object. For example, `query2.run()` returns a Promise object. |
| 66 | + |
| 67 | +```javascript |
| 68 | +return query2.run() |
| 69 | +``` |
| 70 | + |
| 71 | +{% hint style="info" %} |
| 72 | +The `return` statement is not necessary for scenarios where you want to omit results. |
| 73 | +{% endhint %} |
| 74 | + |
| 75 | +### Access data |
| 76 | + |
| 77 | +Use JS queries to access data in your app. Notice that there's no need to use `{{ }}` notation. |
| 78 | +
|
| 79 | +```javascript |
| 80 | +var data = [input1.value, query1.data, fileUpload.files[0].name]; |
| 81 | +``` |
| 82 | +
|
| 83 | +### Control component |
| 84 | +
|
| 85 | +In JS queries, you can use methods exposed by components to interact with UI components in your app. Such operation is not supported by the inline JS code in `{{}}`. |
| 86 | +
|
| 87 | +```javascript |
| 88 | +// set the value of input1 to "Hello" |
| 89 | +input1.setValue("Hello"); |
| 90 | +``` |
| 91 | +
|
| 92 | +{% hint style="warning" %} |
| 93 | +The `input1.setValue()` method (or other component methods) is asynchronous and returns a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/Promise) object. Accessing `input1.value` immediately after setting the value of `input1` does not return the updated value. |
| 94 | +{% endhint %} |
| 95 | +
|
| 96 | +### Run query |
| 97 | +
|
| 98 | +#### `run()` method and callbacks |
| 99 | +
|
| 100 | +Call `run()` method to run other queries, for example: |
| 101 | +
|
| 102 | +```javascript |
| 103 | +return queryByName.run(); // run a query and it returns a Promise |
| 104 | +``` |
| 105 | +
|
| 106 | +The return value of `query.run()` is a Promise, so you can attach callbacks to handle the successful result or error. |
| 107 | +
|
| 108 | +```javascript |
| 109 | +return queryByName.run().then( |
| 110 | + data => { // after query runs successfully |
| 111 | + return "hello, " + data.user_fullname; |
| 112 | + }, |
| 113 | + error => { // after query runs in failure |
| 114 | + // use built-in message function to pop up an error message |
| 115 | + message.error("An error occured when fetching user: " + error.message); |
| 116 | + } |
| 117 | +); |
| 118 | +``` |
| 119 | +
|
| 120 | +#### Pass in parameters |
| 121 | +
|
| 122 | +You can pass parametes in the `run()` method to decouple query implementation from its parameters. |
| 123 | +
|
| 124 | +```javascript |
| 125 | +query.run({ |
| 126 | + param1: value1, |
| 127 | + param2: value2 |
| 128 | + ... |
| 129 | +}); |
| 130 | +``` |
| 131 | +
|
| 132 | +For example, in SQL query `query1`, you can define `name` and `status` as parameters that need to be passed in for its execution. |
| 133 | +
|
| 134 | +```sql |
| 135 | +select * from users |
| 136 | + where |
| 137 | + user_name = {{ name }} |
| 138 | + and |
| 139 | + user_status = {{ status }} |
| 140 | +``` |
| 141 | +
|
| 142 | +Then you can pass in corresponding parameters to `query1`. |
| 143 | +
|
| 144 | +```javascript |
| 145 | +query1.run({ |
| 146 | + name: "Bob", |
| 147 | + status: 0 |
| 148 | +}).then( |
| 149 | + data => { // after query1 runs successfully |
| 150 | + console.log("The result is" + JSON.stringify(data)); |
| 151 | + }, |
| 152 | + error => { // after query1 runs failed |
| 153 | + console.log("An error occured," + error.message); |
| 154 | + } |
| 155 | +); |
| 156 | +``` |
| 157 | +
|
| 158 | +**Demo 1** |
| 159 | +
|
| 160 | +When you have several inputs in an app triggering the same query, passing parameters to this query allows you to reuse it anywhere. |
| 161 | +
|
| 162 | +```sql |
| 163 | +-- query1: |
| 164 | +select id, name, gender, address from users where id={{numberInput1.value}} |
| 165 | +-- query2: |
| 166 | +select id, name, gender, address from users where id={{table1.selectedRow.id}} |
| 167 | +-- query3: |
| 168 | +select id, name, gender, address from users where id={{select1.value}} |
| 169 | +... |
| 170 | +``` |
| 171 | +
|
| 172 | +Things might get fuzzy when you want to update SQL implementations, because you have to carefully check and update all duplicated queries. Now you can be relieved of this repeated SQL by introducing query parameters. |
| 173 | +
|
| 174 | +```sql |
| 175 | +-- just write the SQL once, and extract its parameter {{id}}: |
| 176 | +select id, name, gender, address from users where id= {{id}} |
| 177 | +``` |
| 178 | +
|
| 179 | +Then trigger this query in **Run JavaScript** of event handlers in each of the inputs. |
| 180 | +
|
| 181 | +<figure><img src="../../.gitbook/assets/js-query-3.png" alt=""><figcaption></figcaption></figure> |
| 182 | +
|
| 183 | +**Demo 2** |
| 184 | +
|
| 185 | +You can find another demo for using passed-in paramter queries [here](https://cloud.openblocks.dev/apps/637f38daa899fe1ffcb17f0b/view). |
| 186 | +
|
| 187 | +### Declare a function |
| 188 | +
|
| 189 | +You can declare functions inside a JS query for better readability. |
| 190 | +
|
| 191 | +```javascript |
| 192 | +// Whether the first number is a multiple of the second number |
| 193 | +function isMultiple(num1, num2) { |
| 194 | + return num1 % num2 === 0; |
| 195 | + } |
| 196 | + |
| 197 | +// Call the moment library to return the current date |
| 198 | +function getCurrentDate() { |
| 199 | + return moment().format("YYYY-MM-DD"); |
| 200 | +} |
| 201 | +``` |
| 202 | +
|
| 203 | +## Customized scripting |
| 204 | +
|
| 205 | +Openblocks supports importing third-party JS libraries and adding predefined JS code, such as adding global methods or variables for reuse either at **app-level** or **workspace-level**. You can find the app-level settings in ⚙️ > **Other** > **Scripts and style**. |
| 206 | +
|
| 207 | +<figure><img src="../../.gitbook/assets/js-query-4.png" alt=""><figcaption></figcaption></figure> |
| 208 | +
|
| 209 | +For workspace-level, go to ⚙️ **Settings** > **Advanced**. |
| 210 | +
|
| 211 | +<figure><img src="../../.gitbook/assets/js-query-5.png" alt=""><figcaption></figcaption></figure> |
| 212 | +
|
| 213 | +### Import JS library |
| 214 | +
|
| 215 | +Openblocks supports setting up preloaded JS libraries. For detailed information, see [use-third-party-libraries.md](../use-third-party-libraries.md "mention"). |
| 216 | +
|
| 217 | +<figure><img src="../../.gitbook/assets/js-query-6.png" alt=""><figcaption></figcaption></figure> |
| 218 | +
|
| 219 | +### Define global methods and variables |
| 220 | +
|
| 221 | +In **JavaScript** tab, you can add preloaded JavaScript code to define global methods and variables and then reuse them in your app. |
| 222 | +
|
| 223 | +<figure><img src="../../.gitbook/assets/js-query-7.png" alt=""><figcaption></figcaption></figure> |
| 224 | +
|
| 225 | +<figure><img src="../../.gitbook/assets/js-query-8.png" alt=""><figcaption></figcaption></figure> |
| 226 | +
|
| 227 | +## Restrictions |
| 228 | +
|
| 229 | +For security reasons, several global variables and functions of **window** are disabled in Openblocks. Please report to our [GitHub](https://github.com/openblocks-dev/openblocks) or [Discord](https://discord.com/invite/z5W2YHXdtt) if you encounter any issues. |
0 commit comments