All files / JsonApiClient QueryBuilder.ts

100% Statements 64/64
100% Branches 58/58
100% Functions 15/15
100% Lines 64/64

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223                                                1x                                                                                       21x 21x 21x       5x   5x       6x   6x       1x   1x       1x   1x       5x   5x       5x   5x       6x 6x   6x 4x 4x   2x 2x     6x       1x   1x       5x   5x       23x       4x 4x   4x       16x   16x             20x       20x 4x 4x 5x 5x   4x           20x 4x 4x 4x 9x 9x     9x   4x         20x 3x 3x 4x 4x   3x 3x         20x 3x 3x         20x 3x 3x     20x             16x      
/**
 * Copyright 2015-2018 info@neomerx.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
import { FieldParameterInterface } from '../Contracts/JsonApiClient/FieldParameterInterface';
import { FilterParameterInterface } from '../Contracts/JsonApiClient/FilterParameterInterface';
import { QueryBuilderInterface } from '../Contracts/JsonApiClient/QueryBuilderInterface';
import { SortParameterInterface } from '../Contracts/JsonApiClient/SortParameterInterface';
import { RelationshipName } from '../Contracts/JsonApi/RelationshipName';
import { ResourceIdentity } from '../Contracts/JsonApi/ResourceIdentity';
import { ResourceType } from '../Contracts/JsonApi/ResourceType';
 
export class QueryBuilder implements QueryBuilderInterface {
    /**
     * @internal
     */
    private type: ResourceType;
 
    /**
     * @internal
     */
    private fields: FieldParameterInterface[] | undefined;
 
    /**
     * @internal
     */
    private filters: FilterParameterInterface[] | undefined;
 
    /**
     * @internal
     */
    private useAndWithFilters: boolean;
 
    /**
     * @internal
     */
    private sorts: SortParameterInterface[] | undefined;
 
    /**
     * @internal
     */
    private includes: RelationshipName[] | undefined;
 
    /**
     * @internal
     */
    private offset: number | undefined;
 
    /**
     * @internal
     */
    private limit: number | undefined;
 
    private isEncodeUriEnabled: boolean;
 
    constructor(type: ResourceType) {
        this.useAndWithFilters = true;
        this.isEncodeUriEnabled = true;
        this.type = type;
    }
 
    public onlyFields(...fields: FieldParameterInterface[]): QueryBuilderInterface {
        this.fields = fields;
 
        return this;
    }
 
    public withFilters(...filters: FilterParameterInterface[]): QueryBuilderInterface {
        this.filters = filters;
 
        return this;
    }
 
    public combineFiltersWithAnd(): QueryBuilderInterface {
        this.useAndWithFilters = true;
 
        return this;
    }
 
    public combineFiltersWithOr(): QueryBuilderInterface {
        this.useAndWithFilters = false;
 
        return this;
    }
 
    public withSorts(...sorts: SortParameterInterface[]): QueryBuilderInterface {
        this.sorts = sorts;
 
        return this;
    }
 
    public withIncludes(...relationships: RelationshipName[]): QueryBuilderInterface {
        this.includes = relationships;
 
        return this;
    }
 
    public withPagination(offset: number, limit: number): QueryBuilderInterface {
        offset = Math.max(-1, Math.floor(offset));
        limit = Math.max(0, Math.floor(limit));
 
        if (offset >= 0 && limit > 0) {
            this.offset = offset;
            this.limit = limit;
        } else {
            this.offset = undefined;
            this.limit = undefined;
        }
 
        return this;
    }
 
    public enableEncodeUri(): QueryBuilderInterface {
        this.isEncodeUriEnabled = true;
 
        return this;
    }
 
    public disableEncodeUri(): QueryBuilderInterface {
        this.isEncodeUriEnabled = false;
 
        return this;
    }
 
    public isUriEncodingEnabled(): boolean {
        return this.isEncodeUriEnabled;
    }
 
    public read(index: ResourceIdentity, relationship?: RelationshipName): string {
        const relationshipTail = relationship === undefined ? `/${index}` : `/${index}/${relationship}`;
        const result = `/${this.type}${relationshipTail}${this.buildParameters(false)}`;
 
        return this.isUriEncodingEnabled() === true ? encodeURI(result) : result;
    }
 
    public index(): string {
        const result = `/${this.type}${this.buildParameters(true)}`;
 
        return this.isUriEncodingEnabled() === true ? encodeURI(result) : result;
    }
 
    /**
     * @internal
     */
    private buildParameters(isIncludeNonFields: boolean): string {
        let params = null;
 
        // add field params to get URL like '/articles?include=author&fields[articles]=title,body&fields[people]=name'
        // see http://jsonapi.org/format/#fetching-sparse-fieldsets
        if (this.fields !== undefined && this.fields.length > 0) {
            let fieldsResult = '';
            for (let field of this.fields) {
                const curResult = `fields[${field.type}]=${QueryBuilder.separateByComma(field.fields)}`;
                fieldsResult = fieldsResult.length === 0 ? curResult : `${fieldsResult}&${curResult}`;
            }
            params = fieldsResult;
        }
 
        // add filter parameters to get URL like 'filter[id][greater-than]=10&filter[id][less-than]=20&filter[title][like]=%Typ%'
        // filters could be joined with `AND` (default) / `OR` (e.g. filter[or][field][operation]=...&filter[or][...]...)
        // note: the spec do not specify format for filters http://jsonapi.org/format/#fetching-filtering
        if (isIncludeNonFields === true && this.filters !== undefined && this.filters.length > 0) {
            let filtersResult = '';
            const operationPrefix = this.useAndWithFilters === true ? '' : '[or]';
            for (let filter of this.filters) {
                const params = filter.parameters;
                const curResult = params === undefined ?
                    `filter${operationPrefix}[${filter.field}][${filter.operation}]` :
                    `filter${operationPrefix}[${filter.field}][${filter.operation}]=${QueryBuilder.separateByComma(params)}`;
                filtersResult = filtersResult.length === 0 ? curResult : `${filtersResult}&${curResult}`;
            }
            params = params === null ? filtersResult : `${params}&${filtersResult}`;
        }
 
        // add sorts to get URL like '/articles?sort=-created,title'
        // see http://jsonapi.org/format/#fetching-sorting
        if (isIncludeNonFields === true && this.sorts !== undefined && this.sorts.length > 0) {
            let sortsList = '';
            for (let sort of this.sorts) {
                const sortParam = `${sort.isAscending === true ? '' : '-'}${sort.field}`;
                sortsList = sortsList.length > 0 ? `${sortsList},${sortParam}` : sortParam;
            }
            const sortsResult = `sort=${sortsList}`;
            params = params === null ? sortsResult : `${params}&${sortsResult}`;
        }
 
        // add includes to get URL like '/articles/1?include=author,comments.author'
        // see http://jsonapi.org/format/#fetching-includes
        if (isIncludeNonFields === true && this.includes !== undefined && this.includes.length > 0) {
            const includesResult = `include=${QueryBuilder.separateByComma(this.includes)}`;
            params = params === null ? includesResult : `${params}&${includesResult}`;
        }
 
        // add pagination to get URL like '/articles?page[offset]=50&page[limit]=25'
        // note: the spec do not strictly define pagination parameters
        if (isIncludeNonFields === true && this.offset !== undefined && this.limit !== undefined) {
            const paginationResult = `page[offset]=${this.offset}&page[limit]=${this.limit}`;
            params = params === null ? paginationResult : `${params}&${paginationResult}`;
        }
 
        return params === null ? '' : `?${params}`;
    }
 
    /**
     * @internal
     */
    private static separateByComma(values: string | string[]): string {
        return Array.isArray(values) === true ? (<string[]>values).join(',') : `${<string>values}`;
    }
}