UNPKG

@discoveryjs/discovery

Version:

Frontend framework for rapid data (JSON) analysis, shareable serverless reports and dashboards

43 lines (42 loc) 1.72 kB
import jora from "jora"; export function queryToConfig(view, query) { const { ast } = jora.syntax.parse(query); const config = { view }; if (ast.type !== "Block") { throw new SyntaxError('[Discovery] ViewModel#queryToConfig(): query root must be a "Block"'); } if (ast.body.type !== "Object") { throw new SyntaxError('[Discovery] ViewModel#queryToConfig(): query root must return an "Object"'); } for (const entry of ast.body.properties) { if (entry.type !== "ObjectEntry") { throw new SyntaxError('[Discovery] ViewModel#queryToConfig(): unsupported object entry type "' + entry.type + '"'); } let key; let value = entry.value; switch (entry.key.type) { case "Literal": key = entry.key.value; break; case "Identifier": key = entry.key.name; value ||= entry.key; break; case "Reference": key = entry.key.name.name; value ||= entry.key; break; default: throw new SyntaxError('[Discovery] ViewModel#queryToConfig(): unsupported object key type "' + entry.key.type + '"'); } if (key === "view" || key === "postRender") { throw new SyntaxError('[Discovery] ViewModel#queryToConfig(): set a value for "' + key + '" property in shorthand notation is prohibited'); } if (key === "when" || key === "data" || key === "whenData") { config[key] = value.type === "Literal" && typeof value.value !== "string" ? value.value : jora.syntax.stringify(value); } else { config[key] = value.type === "Literal" && (typeof value.value !== "string" || value.value[0] !== "=") ? value.value : "=" + jora.syntax.stringify(value); } } return config; }