Add type validation for filter
This commit is contained in:
@@ -3,6 +3,14 @@ import { adapters } from "../adapters";
|
|||||||
import { DummyOpenHAB, OpenHAB } from "../openhab";
|
import { DummyOpenHAB, OpenHAB } from "../openhab";
|
||||||
|
|
||||||
|
|
||||||
|
const createFilter = (filter?: string) => {
|
||||||
|
if(!filter) {
|
||||||
|
return (_: Thing) => true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Function("$", `const v = ${filter}; if(typeof v !== 'boolean') throw new Error("Filter should be of boolean type"); return v;`) as ((_: Thing) => true);
|
||||||
|
};
|
||||||
|
|
||||||
export const importThings = async (config: Config, options: ImportOptions) => {
|
export const importThings = async (config: Config, options: ImportOptions) => {
|
||||||
const OH = options.dryRun ? DummyOpenHAB : OpenHAB;
|
const OH = options.dryRun ? DummyOpenHAB : OpenHAB;
|
||||||
const openhab = new OH(config.openHAB);
|
const openhab = new OH(config.openHAB);
|
||||||
@@ -24,9 +32,7 @@ export const importThings = async (config: Config, options: ImportOptions) => {
|
|||||||
const existingThings = await openhab.getThings();
|
const existingThings = await openhab.getThings();
|
||||||
const existingThingsUIDs = existingThings.map(t => t.UID);
|
const existingThingsUIDs = existingThings.map(t => t.UID);
|
||||||
|
|
||||||
const filter: (thing: Thing) => boolean = options.where
|
const filter = createFilter(options.where);
|
||||||
? (new Function("$", `return ${options.where}`)) as ((_: Thing) => true)
|
|
||||||
: (_: Thing) => true;
|
|
||||||
|
|
||||||
const thingsToImport = things
|
const thingsToImport = things
|
||||||
.filter(t => !existingThingsUIDs.includes(t.UID))
|
.filter(t => !existingThingsUIDs.includes(t.UID))
|
||||||
@@ -39,4 +45,4 @@ export const importThings = async (config: Config, options: ImportOptions) => {
|
|||||||
await openhab.createThings(...thingsToImport);
|
await openhab.createThings(...thingsToImport);
|
||||||
|
|
||||||
return thingsToImport;
|
return thingsToImport;
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user