Skip to content

Commit 20e9686

Browse files
authored
Allow filter functions to be async (#597)
* allow fn filter as async function, to make it possible to dynamically fetch data from services * docs for async fn
1 parent 90b8f8c commit 20e9686

2 files changed

Lines changed: 17 additions & 3 deletions

File tree

readme.md

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -638,6 +638,20 @@ entities:
638638
- map_y: parseFloat(y) * parseFloat(hass.states['sensor.cost'].state)
639639
```
640640

641+
This can also be used to fetch data by calling a HA service. As this is a call that requires a network connection, the function needs to be defined `async`:
642+
```yaml
643+
filters:
644+
- fn: |-
645+
async ({xs, ys, meta, hass}) => {
646+
const weather = await hass.callService("weather", "get_forecasts", {type: "hourly"}, {entity_id:"weather.home"}, true, true)
647+
const home = weather.response["weather.home"].forecast
648+
return {
649+
xs: home.map(h => new Date(h.datetime)),
650+
ys: home.map(h => h.temperature)
651+
}
652+
}
653+
```
654+
641655
##### Using vars
642656

643657
Compute absolute humidity

src/parse-config/parse-config.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -161,7 +161,7 @@ class ConfigParser {
161161
value = parent[key];
162162

163163
if (path.match(/^entities\.\d+\.filters\.\d+$/)) {
164-
this.evalFilter({ parent, path, key, value });
164+
await this.evalFilter({ parent, path, key, value });
165165
}
166166
if (path.match(/^entities\.\d+$/)) {
167167
if (!this.fnParam.xs) {
@@ -330,7 +330,7 @@ class ConfigParser {
330330
}
331331
return value;
332332
}
333-
private evalFilter(input: {
333+
private async evalFilter(input: {
334334
parent: object;
335335
path: string;
336336
key: string;
@@ -356,7 +356,7 @@ class ConfigParser {
356356
}
357357
const filterfn = config === null ? filter() : filter(config);
358358
try {
359-
const r = filterfn(this.fnParam);
359+
const r = await filterfn(this.fnParam);
360360
for (const key in r) {
361361
this.fnParam[key] = r[key];
362362
}

0 commit comments

Comments
 (0)