feat(jslib): or/and/not/join query builder support

refactor/addresses-js
Tomáš Mládek 2023-11-18 13:51:21 +01:00
parent be45fcdac5
commit 779015ae32
2 changed files with 62 additions and 0 deletions

View File

@ -60,6 +60,30 @@ export class Query {
return query;
}
public static or(...queries: Query[]): Query {
const query = new Query();
query._query = `(or ${queries.join(" ")})`;
return query;
}
public static and(...queries: Query[]): Query {
const query = new Query();
query._query = `(and ${queries.join(" ")})`;
return query;
}
public static not(query: Query): Query {
const q = new Query();
q._query = `(not ${query})`;
return q;
}
public static join(...queries: Query[]): Query {
const query = new Query();
query._query = `(join ${queries.join(" ")})`;
return query;
}
public toString(): string {
if (!this._query) throw new Error("Query is not defined");
return this._query;

View File

@ -36,3 +36,41 @@ test("query matches variables", (t) => {
const query = Query.matches("entity", "attribute", Variable("a"));
t.is(query.toString(), '(matches entity "attribute" ?a)');
});
test("OR queries", (t) => {
const query = Query.or(
Query.matches("entity", "attribute1", "value2"),
Query.matches("entity", "attribute2", "value2")
);
t.is(
query.toString(),
'(or (matches entity "attribute1" "value2") (matches entity "attribute2" "value2"))'
);
});
test("AND queries", (t) => {
const query = Query.and(
Query.matches("entity", "attribute1", "value2"),
Query.matches("entity", "attribute2", "value2")
);
t.is(
query.toString(),
'(and (matches entity "attribute1" "value2") (matches entity "attribute2" "value2"))'
);
});
test("NOT query", (t) => {
const query = Query.not(Query.matches("entity", "attribute1", "value2"));
t.is(query.toString(), '(not (matches entity "attribute1" "value2"))');
});
test("JOIN queries", (t) => {
const query = Query.join(
Query.matches("entity", "attribute1", "value2"),
Query.matches("entity", "attribute2", "value2")
);
t.is(
query.toString(),
'(join (matches entity "attribute1" "value2") (matches entity "attribute2" "value2"))'
);
});