All files / src/Query QueryBuilder.ts

100% Statements 12/12
0% Branches 0/1
100% Functions 7/7
100% Lines 11/11
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64          1x                         1x 39x             85x               84x       39x 39x                     4x 4x         4x 5x            
/**
 * @module Query
 */ /** */
 
import { Observable } from 'rxjs/Observable';
import { QueryExpression, QueryResult, QuerySegment } from '.';
import { IContent } from '../Content';
import { IODataParams } from '../ODataApi';
import { BaseRepository } from '../Repository/BaseRepository';
 
/**
 * Represents an instance of a Query expression.
 * Usage example:
 * ```ts
 * const query = new Query(q => q.TypeIs(ContentTypes.Task).And.Equals('DisplayName', 'Test'))
 * console.log(query.toString());   // the content query expression
 * ```
 */
export class QueryBuilder<T extends IContent = IContent> {
    private readonly _segments: QuerySegment<T>[] = [];
 
    /**
     * Appends a new QuerySegment to the existing Query
     * @param {QuerySegment<T>} newSegment The Segment to be added
     */
    public AddSegment(newSegment: QuerySegment<T> ) {
        this._segments.push(newSegment);
    }
 
    /**
     * @returns {String} The Query expression as a sensenet Content Query
     */
    // tslint:disable-next-line:naming-convention
    public toString(): string {
        return this._segments.map((s) => s.toString()).join('');
    }
 
    constructor(build: (first: QueryExpression<T>) => void) {
        const firstExpression = new QueryExpression<T>(this);
        build(firstExpression);
    }
 
    /**
     * Method that executes the Query and creates an OData request
     * @param {BaseRepository} repository The Repository instance
     * @param {string} path The Path for the query
     * @param {ODataParams} odataParams Additional OData parameters (like $select, $expand, etc...)
     * @returns {Observable<QueryResult<TReturns>>} An Observable that will publish the Query result
     */
    public Exec(repository: BaseRepository, path: string, odataParams: IODataParams<T> = {}): Observable<QueryResult<T>> {
        odataParams.query = this.toString();
        return repository.GetODataApi().Fetch<T>({
                path,
                params: odataParams
            })
            .map((q) => {
                return {
                    Result: q.d.results.map((c) => repository.HandleLoadedContent<T>(c)),
                    Count: q.d.__count
                };
            });
    }
}