import { Config, ImportOptions, Thing } from "@types"; import { adapters } from "../adapters"; 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) => { const OH = options.dryRun ? DummyOpenHAB : OpenHAB; const openhab = new OH(config.openHAB); const sources = options.sources ?? Object.keys(config.sources); const things = (await Promise.all(sources.map(source => { const { type, config: cfg } = config.sources[source]; const constructor = adapters[type as keyof (typeof adapters)]; if (!constructor) { throw new Error(`Unknown source type '${type}'`); } return new constructor(source, cfg).loadThings(); }))).flat(); const existingThings = await openhab.getThings(); const existingThingsUIDs = existingThings.map(t => t.UID); const filter = createFilter(options.where); const thingsToImport = things .filter(t => !existingThingsUIDs.includes(t.UID)) .filter(filter); if (options.force) { await openhab.deleteThings(...thingsToImport.map(t => t.UID)); } await openhab.createThings(...thingsToImport); return thingsToImport; }