Source

models/query/osduQueryExpression.js

/**
 * Class to build OSDU query expressions from strings or by concatenating two other OSDU query expressions
 * - Serves as a builder for the [text queries]{@link https://community.opengroup.org/osdu/documentation/-/wikis/Releases/R2.0/OSDU-Query-Syntax#text-queries} within the OSDU query syntax
 * @class
 * @category Models
 * @subcategory Query
 */
class OsduQueryExpression {
    /**
     * Constructor for free-form query expressions
     * - Often used for base expressions such as `data.ResourceID:\"...\"`
     * @param {string} statement - A string statement representing a single boolean query statement
     */
    constructor(statement) {
        if (!(typeof statement === 'string' || statement instanceof String)) {
            throw new Error(`OsduQueryExpression with statement must pass a string`);
        }
        this.statement = statement;
    }

    /**
     * Builder method to simplify the concatenation of multiple query expressions while providing clear scoping boundaries
     * @static
     * @param {string} boolean_operator - The concatenating operator. Accepts `"AND"` or `"OR"`
     * @param {OsduQueryExpression} left_expression - The query expression on the left hand side of the boolean operator
     * @param {OsduQueryExpression} right_expression - the query expression on the right hand side of the boolean operator
     * @returns {OsduQueryExpression} The resulting compound query expression generated by concatenating the provided query expressions
     */
    static FromOperator(boolean_operator, left_expression, right_expression) {
        if (!(left_expression instanceof OsduQueryExpression) || !(right_expression instanceof OsduQueryExpression)) {
            throw new Error(`OsduQueryExpression with boolean operator must contain both left and right OsduQueryExpressions`);
        }
        var statement = "";
        switch(boolean_operator) {
            case "AND":
                statement = `(${left_expression.toString()} AND ${right_expression.toString()})`;
                break;
            case "OR":
                statement = `(${left_expression.toString()} OR ${right_expression.toString()})`;
                break;
            default:
                throw new Error(`Unknown boolean operator in OsduQueryExpression: ${boolean_operator}`);
        }
        return new OsduQueryExpression(statement);
    }

    /**
     * Stringification method used to convert the expression to a string when formulating the API query statement
     * @returns {string} The string representation of the query statement
     */
    toString() {
        return this.statement;
    }
}

module.exports = OsduQueryExpression;