feat(jslib): add variables to jslib query builder

feat/selector-improvements
Tomáš Mládek 2023-11-11 11:17:43 +01:00
parent 6f00c2f583
commit 838ce28647
2 changed files with 19 additions and 2 deletions

View File

@ -2,7 +2,13 @@ import type { Address } from "./types";
import { isAddress } from "./types";
export const Any = "?";
type QueryPart<T> = T | T[] | typeof Any;
class Var {
constructor(public readonly name: string) {}
}
export function Variable(name: string): Var {
return new Var(name);
}
type QueryPart<T> = T | T[] | typeof Any | Var;
export class Query {
private _query: string | undefined;
@ -17,6 +23,8 @@ export class Query {
let entityStr;
if (entity === Any) {
entityStr = "?";
} else if (entity instanceof Var) {
entityStr = `?${entity.name}`;
} else {
entityStr = Array.isArray(entity) ? `(in ${entity.join(" ")})` : entity;
}
@ -24,6 +32,8 @@ export class Query {
let attributeStr;
if (attribute === Any) {
attributeStr = "?";
} else if (attribute instanceof Var) {
attributeStr = `?${attribute.name}`;
} else {
attributeStr = Array.isArray(attribute)
? `(in ${attribute.map((a) => `"${a}"`).join(" ")})`
@ -33,6 +43,8 @@ export class Query {
let valueStr;
if (value === Any) {
valueStr = "?";
} else if (value instanceof Var) {
valueStr = `?${value.name}`;
} else {
valueStr = (Array.isArray(value) ? value : [value])
.map((v) => {

View File

@ -1,5 +1,5 @@
import test from "ava";
import { Any, Query } from "./query";
import { Any, Query, Variable } from "./query";
test("query matches simple", (t) => {
const query = Query.matches("entity", "attribute", "value");
@ -31,3 +31,8 @@ test("query matches numbers", (t) => {
const query = Query.matches("entity", "attribute", [1, 2]);
t.is(query.toString(), '(matches entity "attribute" (in 1 2))');
});
test("query matches variables", (t) => {
const query = Query.matches("entity", "attribute", Variable("a"));
t.is(query.toString(), '(matches entity "attribute" ?a)');
});