├── .gitignore ├── .npmignore ├── .travis.yml ├── README.md ├── package-lock.json ├── package.json ├── prettier.config.js ├── src ├── enums.ts ├── queryBuilder.spec.ts ├── queryBuilder.ts ├── queryFragment.ts └── testing │ ├── index.ts │ ├── testCase.ts │ └── testCaseCollection.ts ├── tsconfig.json ├── tslint.json └── webpack.config.js /.gitignore: -------------------------------------------------------------------------------- 1 | .vs/ 2 | dist/ 3 | node_modules/ 4 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | .vs/ 2 | node_modules/ 3 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | branches: 3 | only: 4 | - master 5 | - /^greenkeeper/.*$/ 6 | cache: 7 | yarn: true 8 | directories: 9 | - node_modules 10 | notifications: 11 | email: false 12 | node_js: 13 | - node 14 | script: 15 | - npm run lint && npm run ci && npm run build -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Recently patched and updated! Looking For Contributors. 2 | 3 | # odata-query-builder 4 | An eloquently fluent OData query builder. 5 | 6 | [![Build Status](https://travis-ci.org/jaredmahan/angular-searchFilter.svg?branch=master)](https://travis-ci.org/jaredmahan/odata-query-builder) 7 | [![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg)](http://standardjs.com/) 8 | 9 | ## Install 10 | ``` 11 | yarn add odata-query-builder 12 | ``` 13 | or 14 | ``` 15 | npm install --save odata-query-builder 16 | ``` 17 | 18 | ### Then in your code... 19 | ``` 20 | const query = new QueryBuilder() 21 | .count() 22 | .top(5) 23 | .skip(5) 24 | .expand('NavigationProp') 25 | .orderBy('MyPriorityProp') 26 | .filter(f => f.filterExpression('Property', 'eq', 'MyValue')) 27 | .select('My Properties') 28 | .toQuery() 29 | ``` 30 | 31 | Outputs: 32 | `?$orderby=MyPriorityProp&$top=5&$skip=5&$count=true&$expand=NavigationProp&$filter=Property eq 'MyValue'` 33 | 34 | # Filtering 35 | 36 | ## Filter Expressions 37 | Filter expresssions utilize [logical operators](http://docs.oasis-open.org/odata/odata/v4.01/cs01/part2-url-conventions/odata-v4.01-cs01-part2-url-conventions.html#sec_LogicalOperatorExamples) to filter data on a specific property. 38 | 39 | Operator Options: 40 | - Equal: `eq` 41 | - Not Eqaul: `ne` 42 | - Greater Than: `gt` 43 | - Greater Than or Equal: `ge` 44 | - Less Than: `lt` 45 | - Less Than or Equal: `le` 46 | 47 | ``` 48 | const query = new QueryBuilder() 49 | .filter(f => 50 | f.filterExpression('Property1', 'eq', 'Value1') 51 | ).ToQuery(); 52 | ``` 53 | Outputs: `?$filter=Property1 eq 'Value1'` 54 | 55 | ## Filter Phrases 56 | Filter phrases are meant to be used with [canonical functions](http://docs.oasis-open.org/odata/odata/v4.01/cs01/part2-url-conventions/odata-v4.01-cs01-part2-url-conventions.html#sec_CanonicalFunctions). Filter Phrasing exposes the filter as a string which allows you to inject any of the various filtering mechanisms available in `OData v4`. 57 | 58 | Below are a few examples: 59 | 60 | ``` 61 | const query = new QueryBuilder() 62 | .filter(f => 63 | .filter(f => 64 | f 65 | .filterPhrase(`contains(Property1,'Value1')`) 66 | .filterPhrase(`startswith(Property1,'Value1')`) 67 | .filterPhrase(`endswith(Property1,'Value1')`) 68 | .filterPhrase(`indexOf(Property1,'Value1') eq 1`) 69 | .filterPhrase(`length(Property1) eq 19`) 70 | .filterPhrase(`substring(Property1, 1, 2) eq 'ab'`) 71 | ).ToQuery(); 72 | ``` 73 | Outputs: `?$filter=contains(Property1,'Value1') and startswith(Property1,'Value1') and endswith(Property1,'Value1') and indexOf(Property1,'Value1') eq 1 and length(Property1) eq 19 and substring(Property1, 1, 2) eq 'ab` 74 | 75 | ## Conditional Filtering Operators 76 | By default when you utilize `.filter` you are using the `and` operator. You can be explict by passing your operator into the filter as a secondary parameter. 77 | ``` 78 | const query = new QueryBuilder().filter(f => f 79 | .filterExpression('Property1', 'eq', 'Value1') 80 | .filterExpression('Property2', 'eq', 'Value1'), 81 | 'and' 82 | ).toQuery(); 83 | ``` 84 | Outputs: `?$filter=Property1 eq 'Value1' and Property2 eq 'Value1'` 85 | ``` 86 | const query = new QueryBuilder().filter(f => f 87 | .filterExpression('Property1', 'eq', 'Value1') 88 | .filterExpression('Property2', 'eq', 'Value1'), 89 | 'or' 90 | ).toQuery(); 91 | ``` 92 | Outputs: `?$filter=Property1 eq 'Value1' or Property2 eq 'Value1'` 93 | 94 | ## Nested Filter Chaining 95 | Nested or [grouped](http://docs.oasis-open.org/odata/odata/v4.01/cs01/part2-url-conventions/odata-v4.01-cs01-part2-url-conventions.html#sec_Grouping) filtering is used when we need to write a more complex filter for a data set. This can be done by utilizing `.and()` or `.or()` with the filter. 96 | ``` 97 | const query = new QueryBuilder().filter(f => f 98 | .filterExpression('Property1', 'eq', 'Value1') 99 | .filterExpression('Property2', 'eq', 'Value2') 100 | .and(f1 => f1 101 | .filterExpression('Property3', 'eq', 'Value3') 102 | .filterExpression('Property4', 'eq', 'Value4') 103 | ) 104 | ).toQuery(); 105 | ``` 106 | Outputs: `?$filter=Property1 eq 'Value1' and Property2 eq 'Value2' and (Property3 eq 'Value3' and Property4 eq 'Value4')` 107 | 108 | ``` 109 | const query = new QueryBuilder().filter(f => f 110 | .filterExpression('Property1', 'eq', 'Value1') 111 | .filterExpression('Property2', 'eq', 'Value2') 112 | .or(f1 => f1 113 | .filterExpression('Property3', 'eq', 'Value3') 114 | .filterExpression('Property4', 'eq', 'Value4') 115 | ) 116 | ).toQuery(); 117 | ``` 118 | Outputs: `?$filter=Property1 eq 'Value1' and Property2 eq 'Value2' and (Property3 eq 'Value3' or Property4 eq 'Value4')` 119 | 120 | 121 | ### Reminder: We can still explicitly control the conditional operators within each of the filters by utilizing the filter's condition operator parameter which gives us even more control over the filter. 122 | ``` 123 | const query = new QueryBuilder().filter(f => f 124 | .filterExpression('Property1', 'eq', 'Value1') 125 | .filterExpression('Property2', 'eq', 'Value2') 126 | .or(f1 => f1 127 | .filterExpression('Property3', 'eq', 'Value3') 128 | .filterExpression('Property4', 'eq', 'Value4') 129 | ), 130 | 'and' 131 | ).toQuery(); 132 | ``` 133 | Outputs: `?$filter=Property1 eq 'Value1' and Property2 eq 'Value2' and (Property3 eq 'Value3' or Property4 eq 'Value4')` 134 | 135 | 136 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "odata-query-builder", 3 | "version": "0.0.7", 4 | "description": "An eloquently fluent OData query builder.", 5 | "main": "dist/index.js", 6 | "scripts": { 7 | "build": "webpack", 8 | "lint": "tslint --project tslint.json src/**/**.ts", 9 | "test": "jest --watch", 10 | "coverage": "jest --coverage", 11 | "ci": "jest --coverage --verbose" 12 | }, 13 | "repository": { 14 | "type": "git", 15 | "url": "git+https://github.com/jaredmahan/odata-query-builder.git" 16 | }, 17 | "keywords": [ 18 | "odata", 19 | "odata v4", 20 | "odata client", 21 | "typescript", 22 | "javascript", 23 | "fluent", 24 | "fluent api", 25 | "angular 8", 26 | "angular 7", 27 | "angular 6", 28 | "angular 5", 29 | "angular 2", 30 | "angular 4", 31 | "angular" 32 | ], 33 | "author": "Jared Mahan", 34 | "license": "MIT", 35 | "bugs": { 36 | "url": "https://github.com/jaredmahan/odata-query-builder/issues" 37 | }, 38 | "homepage": "https://github.com/jaredmahan/odata-query-builder#readme", 39 | "devDependencies": { 40 | "@types/jest": "^23.3.1", 41 | "@types/lodash": "^4.14.149", 42 | "@types/lodash.orderby": "^4.6.6", 43 | "@types/node": "^13.1.6", 44 | "awesome-typescript-loader": "^5.2.0", 45 | "dts-bundle": "^0.7.3", 46 | "dts-bundle-webpack": "^1.0.0", 47 | "jest": "^23.4.2", 48 | "lodash.orderby": "^4.6.0", 49 | "source-map-loader": "^0.2.3", 50 | "ts-jest": "^23.0.1", 51 | "tslint": "^5.11.0", 52 | "typescript": "^3.0.1", 53 | "webpack": "^4.16.4", 54 | "webpack-cli": "^3.1.0" 55 | }, 56 | "jest": { 57 | "testURL": "http://localhost/", 58 | "moduleFileExtensions": [ 59 | "ts", 60 | "tsx", 61 | "js" 62 | ], 63 | "roots": [ 64 | "/src/" 65 | ], 66 | "transform": { 67 | "^.+\\.(ts|tsx)$": "ts-jest" 68 | }, 69 | "globals": { 70 | "ts-jest": { 71 | "tsConfigFile": "tsconfig.json" 72 | } 73 | }, 74 | "testMatch": [ 75 | "**/*.spec.+(ts|tsx|js)" 76 | ] 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /prettier.config.js: -------------------------------------------------------------------------------- 1 | // .prettierrc.js 2 | module.exports = { 3 | singleQuote: true, 4 | printWidth: 100 5 | } 6 | -------------------------------------------------------------------------------- /src/enums.ts: -------------------------------------------------------------------------------- 1 | export enum FragmentType { 2 | OrderBy = 1, 3 | Top = 2, 4 | Skip = 3, 5 | Count = 4, 6 | Expand = 5, 7 | Filter = 6, 8 | Select = 7 9 | } 10 | -------------------------------------------------------------------------------- /src/queryBuilder.spec.ts: -------------------------------------------------------------------------------- 1 | import { QueryBuilder } from './queryBuilder'; 2 | import {TestCase, TestCaseCollection} from './testing'; 3 | 4 | describe('Query Builder', () => { 5 | it('should return an empty string when asked to build without options', () => { 6 | expect(new QueryBuilder().toQuery()).toEqual(''); 7 | }); 8 | it('should return count', () => { 9 | expect(new QueryBuilder().count().toQuery()).toEqual('?$count=true'); 10 | }); 11 | it('should return order by', () => { 12 | expect(new QueryBuilder().orderBy('test').toQuery()).toEqual( 13 | '?$orderby=test' 14 | ); 15 | }); 16 | it('should only return the last order by', () => { 17 | expect(new QueryBuilder().orderBy('old').orderBy('test').toQuery()).toEqual( 18 | '?$orderby=test' 19 | ); 20 | }); 21 | it('should return top', () => { 22 | expect(new QueryBuilder().top(1).toQuery()).toEqual('?$top=1'); 23 | }); 24 | it('should only return the last top', () => { 25 | expect(new QueryBuilder().top(5).top(1).toQuery()).toEqual( 26 | '?$top=1' 27 | ); 28 | }); 29 | it('should return skip', () => { 30 | expect(new QueryBuilder().skip(1).toQuery()).toEqual('?$skip=1'); 31 | }); 32 | it('should only return the last skip', () => { 33 | expect(new QueryBuilder().skip(5).skip(1).toQuery()).toEqual( 34 | '?$skip=1' 35 | ); 36 | }); 37 | it('should return expand', () => { 38 | expect(new QueryBuilder().expand('test').toQuery()).toEqual( 39 | '?$expand=test' 40 | ); 41 | }); 42 | it('should only return the last expand at the root level', () => { 43 | expect(new QueryBuilder().expand('old').expand('test').toQuery()).toEqual( 44 | '?$expand=test' 45 | ); 46 | }); 47 | it('should return select', () => { 48 | expect(new QueryBuilder().select('test').toQuery()).toEqual( 49 | '?$select=test' 50 | ); 51 | }); 52 | it('should only return the last select at the root level', () => { 53 | expect(new QueryBuilder().select('old').select('test').toQuery()).toEqual( 54 | '?$select=test' 55 | ); 56 | }); 57 | it('should add a new filter expression', () => { 58 | const testCases = new TestCaseCollection([ 59 | new TestCase( 60 | new QueryBuilder() 61 | .filter(f => f.filterExpression('testProp1', 'eq', 'testVal1')) 62 | .toQuery(), 63 | '?$filter=testProp1 eq \'testVal1\'' 64 | ), 65 | new TestCase( 66 | new QueryBuilder() 67 | .filter(f => f.filterExpression('testProp1', 'eq', 1)) 68 | .toQuery(), 69 | '?$filter=testProp1 eq 1' 70 | ), 71 | new TestCase( 72 | new QueryBuilder() 73 | .filter(f => f.filterExpression('testProp1', 'eq', true)) 74 | .toQuery(), 75 | '?$filter=testProp1 eq true' 76 | ), 77 | // TODO: Fix test 78 | // new TestCase( 79 | // new QueryBuilder() 80 | // .filter(f => 81 | // f.filterExpression( 82 | // 'testProp1', 83 | // 'eq', 84 | // new Date(2018, 1, 1, 0, 0, 0, 0) 85 | // ) 86 | // ) 87 | // .toQuery(), 88 | // '?$filter=testProp1 eq 2018-02-01T06:00:00.000Z' 89 | // ) 90 | ]); 91 | 92 | testCases.test(); 93 | }); 94 | it('should add a new filter phrase', () => { 95 | expect( 96 | new QueryBuilder() 97 | .filter(f => f.filterPhrase('contains(\'test\')')) 98 | .toQuery() 99 | ).toEqual('?$filter=contains(\'test\')'); 100 | }); 101 | 102 | it('should add multiple filters (should default to and)', () => { 103 | const testCases = new TestCaseCollection([ 104 | new TestCase( 105 | new QueryBuilder() 106 | .filter(f => 107 | f 108 | .filterExpression('testProp1', 'eq', 'testVal1') 109 | .filterExpression('testProp2', 'eq', 'testVal2') 110 | ) 111 | .toQuery(), 112 | '?$filter=testProp1 eq \'testVal1\' and testProp2 eq \'testVal2\'' 113 | ), 114 | new TestCase( 115 | new QueryBuilder() 116 | .filter(f => 117 | f 118 | .filterPhrase('contains(\'test1\')') 119 | .filterPhrase('contains(\'test2\')') 120 | ) 121 | .toQuery(), 122 | '?$filter=contains(\'test1\') and contains(\'test2\')' 123 | ), 124 | new TestCase( 125 | new QueryBuilder() 126 | .filter(f => 127 | f 128 | .filterExpression('testProp1', 'eq', 'testVal1') 129 | .filterPhrase('contains(\'test\')') 130 | ) 131 | .toQuery(), 132 | '?$filter=testProp1 eq \'testVal1\' and contains(\'test\')' 133 | ) 134 | ]); 135 | testCases.test(); 136 | }); 137 | 138 | it('should add multiple \'and\' filters', () => { 139 | const testCases = new TestCaseCollection([ 140 | new TestCase( 141 | new QueryBuilder() 142 | .filter( 143 | f => 144 | f 145 | .filterExpression('testProp1', 'eq', 'testVal1') 146 | .filterExpression('testProp2', 'eq', 'testVal2'), 147 | 'and' 148 | ) 149 | .toQuery(), 150 | '?$filter=testProp1 eq \'testVal1\' and testProp2 eq \'testVal2\'' 151 | ), 152 | new TestCase( 153 | new QueryBuilder() 154 | .filter( 155 | f => 156 | f 157 | .filterPhrase('contains(\'test1\')') 158 | .filterPhrase('contains(\'test2\')'), 159 | 'and' 160 | ) 161 | .toQuery(), 162 | '?$filter=contains(\'test1\') and contains(\'test2\')' 163 | ), 164 | new TestCase( 165 | new QueryBuilder() 166 | .filter( 167 | f => 168 | f 169 | .filterExpression('testProp1', 'eq', 'testVal1') 170 | .filterPhrase('contains(\'test\')'), 171 | 'and' 172 | ) 173 | .toQuery(), 174 | '?$filter=testProp1 eq \'testVal1\' and contains(\'test\')' 175 | ) 176 | ]); 177 | testCases.test(); 178 | }); 179 | 180 | it('should add multiple \'or\' filters', () => { 181 | const testCases = new TestCaseCollection([ 182 | new TestCase( 183 | new QueryBuilder() 184 | .filter( 185 | f => 186 | f 187 | .filterExpression('testProp1', 'eq', 'testVal1') 188 | .filterExpression('testProp2', 'eq', 'testVal2'), 189 | 'or' 190 | ) 191 | .toQuery(), 192 | '?$filter=testProp1 eq \'testVal1\' or testProp2 eq \'testVal2\'' 193 | ), 194 | new TestCase( 195 | new QueryBuilder() 196 | .filter( 197 | f => 198 | f 199 | .filterPhrase('contains(\'test1\')') 200 | .filterPhrase('contains(\'test2\')'), 201 | 'or' 202 | ) 203 | .toQuery(), 204 | '?$filter=contains(\'test1\') or contains(\'test2\')' 205 | ), 206 | new TestCase( 207 | new QueryBuilder() 208 | .filter( 209 | f => 210 | f 211 | .filterExpression('testProp1', 'eq', 'testVal1') 212 | .filterPhrase('contains(\'test\')'), 213 | 'or' 214 | ) 215 | .toQuery(), 216 | '?$filter=testProp1 eq \'testVal1\' or contains(\'test\')' 217 | ) 218 | ]); 219 | testCases.test(); 220 | }); 221 | it('should add nested \'or\' filters', () => { 222 | const testCases = new TestCaseCollection([ 223 | new TestCase( 224 | new QueryBuilder() 225 | .filter(f1 => 226 | f1 227 | .filterExpression('testProp1', 'eq', 'testVal1') 228 | .or(f2 => 229 | f2 230 | .filterExpression('testProp2', 'eq', 'testVal2') 231 | .filterExpression('testProp3', 'eq', 'testVal3') 232 | ) 233 | ) 234 | .toQuery(), 235 | '?$filter=testProp1 eq \'testVal1\' and (testProp2 eq \'testVal2\' or testProp3 eq \'testVal3\')' 236 | ), 237 | new TestCase( 238 | new QueryBuilder() 239 | .filter( 240 | f1 => 241 | f1 242 | .filterExpression('testProp1', 'eq', 'testVal1') 243 | .or(f2 => 244 | f2 245 | .filterExpression('testProp2', 'eq', 'testVal2') 246 | .filterExpression('testProp3', 'eq', 'testVal3') 247 | ), 248 | 'and' 249 | ) 250 | .toQuery(), 251 | '?$filter=testProp1 eq \'testVal1\' and (testProp2 eq \'testVal2\' or testProp3 eq \'testVal3\')' 252 | ), 253 | new TestCase( 254 | new QueryBuilder() 255 | .filter( 256 | f1 => 257 | f1 258 | .filterExpression('testProp1', 'eq', 'testVal1') 259 | .or(f2 => 260 | f2 261 | .filterExpression('testProp2', 'eq', 'testVal2') 262 | .filterExpression('testProp3', 'eq', 'testVal3') 263 | ), 264 | 'or' 265 | ) 266 | .toQuery(), 267 | '?$filter=testProp1 eq \'testVal1\' or (testProp2 eq \'testVal2\' or testProp3 eq \'testVal3\')' 268 | ) 269 | ]); 270 | testCases.test(); 271 | }); 272 | it('should add nested \'and\' filters', () => { 273 | const testCases = new TestCaseCollection([ 274 | new TestCase( 275 | new QueryBuilder() 276 | .filter(f1 => 277 | f1 278 | .filterExpression('testProp1', 'eq', 'testVal1') 279 | .and(f2 => 280 | f2 281 | .filterExpression('testProp2', 'eq', 'testVal2') 282 | .filterExpression('testProp3', 'eq', 'testVal3') 283 | ) 284 | ) 285 | .toQuery(), 286 | '?$filter=testProp1 eq \'testVal1\' and (testProp2 eq \'testVal2\' and testProp3 eq \'testVal3\')' 287 | ), 288 | new TestCase( 289 | new QueryBuilder() 290 | .filter( 291 | f1 => 292 | f1 293 | .filterExpression('testProp1', 'eq', 'testVal1') 294 | .and(f2 => 295 | f2 296 | .filterExpression('testProp2', 'eq', 'testVal2') 297 | .filterExpression('testProp3', 'eq', 'testVal3') 298 | ), 299 | 'and' 300 | ) 301 | .toQuery(), 302 | '?$filter=testProp1 eq \'testVal1\' and (testProp2 eq \'testVal2\' and testProp3 eq \'testVal3\')' 303 | ), 304 | new TestCase( 305 | new QueryBuilder() 306 | .filter( 307 | f1 => 308 | f1 309 | .filterExpression('testProp1', 'eq', 'testVal1') 310 | .and(f2 => 311 | f2 312 | .filterExpression('testProp2', 'eq', 'testVal2') 313 | .filterExpression('testProp3', 'eq', 'testVal3') 314 | ), 315 | 'or' 316 | ) 317 | .toQuery(), 318 | '?$filter=testProp1 eq \'testVal1\' or (testProp2 eq \'testVal2\' and testProp3 eq \'testVal3\')' 319 | ) 320 | ]); 321 | testCases.test(); 322 | }); 323 | }); 324 | -------------------------------------------------------------------------------- /src/queryBuilder.ts: -------------------------------------------------------------------------------- 1 | import { FragmentType } from './enums'; 2 | import { QueryFragment } from './queryFragment'; 3 | 4 | const orderBy = require('lodash.orderby'); 5 | 6 | type filterExpressionType = string | number | boolean | Date; 7 | 8 | export default class FilterBuilder { 9 | private fragments: QueryFragment[] = []; 10 | filterExpression = (field: string, operator: string, value: filterExpressionType) => { 11 | this.fragments.push( 12 | new QueryFragment(FragmentType.Filter, `${field} ${operator} ${this.getValue(value)}`) 13 | ); 14 | return this; 15 | }; 16 | filterPhrase = (phrase: string) => { 17 | this.fragments.push(new QueryFragment(FragmentType.Filter, phrase)); 18 | return this; 19 | }; 20 | and = (predicate: (filter: FilterBuilder) => FilterBuilder) => { 21 | this.fragments.push( 22 | new QueryFragment(FragmentType.Filter, `(${predicate(new FilterBuilder()).toQuery('and')})`) 23 | ); 24 | return this; 25 | }; 26 | or = (predicate: (filter: FilterBuilder) => FilterBuilder) => { 27 | this.fragments.push( 28 | new QueryFragment(FragmentType.Filter, `(${predicate(new FilterBuilder()).toQuery('or')})`) 29 | ); 30 | return this; 31 | }; 32 | toQuery = (operator: string): string => { 33 | if (!this.fragments || this.fragments.length < 1) return ''; 34 | return this.fragments.map(f => f.value).join(` ${operator} `); 35 | }; 36 | 37 | private getValue(value: filterExpressionType): string { 38 | let type: string = typeof value; 39 | if (value instanceof Date) type = 'date'; 40 | 41 | switch (type) { 42 | case 'string': 43 | return `'${value}'`; 44 | case 'date': 45 | return `${(value as Date).toISOString()}`; 46 | default: 47 | return `${value}`; 48 | } 49 | } 50 | } 51 | 52 | export class QueryBuilder { 53 | private fragments: QueryFragment[] = []; 54 | orderBy = (fields: string) => { 55 | this.clear(FragmentType.OrderBy); 56 | this.fragments.push(new QueryFragment(FragmentType.OrderBy, `$orderby=${fields}`)); 57 | return this; 58 | }; 59 | top = (top: number) => { 60 | this.clear(FragmentType.Top); 61 | this.fragments.push(new QueryFragment(FragmentType.Top, `$top=${top}`)); 62 | return this; 63 | }; 64 | skip = (skip: number) => { 65 | this.clear(FragmentType.Skip); 66 | this.fragments.push(new QueryFragment(FragmentType.Skip, `$skip=${skip}`)); 67 | return this; 68 | }; 69 | count = () => { 70 | this.clear(FragmentType.Count); 71 | this.fragments.push(new QueryFragment(FragmentType.Count, `$count=true`)); 72 | return this; 73 | }; 74 | expand = (fields: string) => { 75 | this.clear(FragmentType.Expand); 76 | this.fragments.push(new QueryFragment(FragmentType.Expand, `$expand=${fields}`)); 77 | return this; 78 | }; 79 | select = (fields: string) => { 80 | this.clear(FragmentType.Select); 81 | this.fragments.push(new QueryFragment(FragmentType.Select, `$select=${fields}`)); 82 | return this; 83 | }; 84 | filter = (predicate: (filter: FilterBuilder) => FilterBuilder, operator: string = 'and') => { 85 | this.clear(FragmentType.Filter); 86 | this.fragments.push( 87 | new QueryFragment(FragmentType.Filter, predicate(new FilterBuilder()).toQuery(operator)) 88 | ); 89 | return this; 90 | }; 91 | clear = (fragmentType: FragmentType) => { 92 | this.fragments = this.fragments.filter(f => f.type !== fragmentType); 93 | return this; 94 | } 95 | toQuery = () => { 96 | if (this.fragments.length < 1) return ''; 97 | 98 | const sortedFragments = orderBy(this.fragments, (sf: QueryFragment) => sf.type); 99 | const nonFilterFragments = sortedFragments.filter((sf: QueryFragment) => sf.type !== FragmentType.Filter); 100 | const filterFragments = sortedFragments.filter((sf: QueryFragment) => sf.type === FragmentType.Filter); 101 | 102 | let query = 103 | '?' + 104 | sortedFragments 105 | .filter((sf: QueryFragment) => sf.type !== FragmentType.Filter) 106 | .map((sf: QueryFragment) => sf.value) 107 | .join('&'); 108 | 109 | if (filterFragments.length < 1) return query; 110 | else if (nonFilterFragments.length > 0) query += '&'; 111 | 112 | query += this.parseFilters(filterFragments, 'and').trim(); 113 | 114 | return query; 115 | }; 116 | 117 | private parseFilters(fragments: QueryFragment[], operator: string): string { 118 | if (!fragments === null || fragments.length < 1) return ''; 119 | return '$filter=' + fragments.map(f => f.value).join(` ${operator} `); 120 | } 121 | } 122 | -------------------------------------------------------------------------------- /src/queryFragment.ts: -------------------------------------------------------------------------------- 1 | import { FragmentType } from './enums'; 2 | 3 | export class QueryFragment { 4 | constructor(public type: FragmentType, public value: string) {} 5 | } 6 | -------------------------------------------------------------------------------- /src/testing/index.ts: -------------------------------------------------------------------------------- 1 | export * from './testCase'; 2 | export * from './testCaseCollection'; 3 | -------------------------------------------------------------------------------- /src/testing/testCase.ts: -------------------------------------------------------------------------------- 1 | export class TestCase { 2 | constructor(public expected: any, public actual: any) {} 3 | } 4 | -------------------------------------------------------------------------------- /src/testing/testCaseCollection.ts: -------------------------------------------------------------------------------- 1 | import { TestCase } from './testCase'; 2 | 3 | export class TestCaseCollection { 4 | constructor(private testCases: TestCase[]) {} 5 | test = () => { 6 | return this.testCases.forEach(tc => expect(tc.expected).toBe(tc.actual)); 7 | }; 8 | } 9 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compileOnSave": false, 3 | "compilerOptions": { 4 | "baseUrl": "./", 5 | "outDir": "./dist", 6 | "strict": true, 7 | "sourceMap": true, 8 | "declaration": true, 9 | "moduleResolution": "node", 10 | "noImplicitAny": true, 11 | "emitDecoratorMetadata": true, 12 | "experimentalDecorators": true, 13 | "target": "esnext", 14 | "typeRoots": ["node_modules/@types"] 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "rules": { 3 | "arrow-parens": [true, "ban-single-arg-parens"], 4 | "arrow-return-shorthand": true, 5 | "callable-types": true, 6 | "class-name": true, 7 | "comment-format": [true, "check-space"], 8 | "curly": [true, "ignore-same-line"], 9 | "deprecation": { 10 | "severity": "warn" 11 | }, 12 | "eofline": true, 13 | "forin": true, 14 | "import-blacklist": [true, "rxjs/Rx"], 15 | "import-spacing": true, 16 | "indent": [true, "spaces"], 17 | "interface-over-type-literal": true, 18 | "label-position": true, 19 | "max-line-length": [true, 140], 20 | "member-access": false, 21 | "member-ordering": [ 22 | true, 23 | { 24 | "order": ["static-field", "instance-field", "static-method", "instance-method"] 25 | } 26 | ], 27 | "no-arg": true, 28 | "no-bitwise": true, 29 | "no-console": [true, "debug", "info", "time", "timeEnd", "trace"], 30 | "no-construct": true, 31 | "no-debugger": true, 32 | "no-duplicate-super": true, 33 | "no-empty": false, 34 | "no-empty-interface": true, 35 | "no-eval": true, 36 | "no-inferrable-types": [true, "ignore-params"], 37 | "no-misused-new": true, 38 | "no-non-null-assertion": true, 39 | "no-shadowed-variable": true, 40 | "no-string-literal": false, 41 | "no-string-throw": true, 42 | "no-switch-case-fall-through": true, 43 | "no-trailing-whitespace": true, 44 | "no-unnecessary-initializer": true, 45 | "no-unused-expression": true, 46 | "no-use-before-declare": true, 47 | "no-var-keyword": true, 48 | "object-literal-sort-keys": false, 49 | "one-line": [true, "check-open-brace", "check-catch", "check-else", "check-whitespace"], 50 | "prefer-const": true, 51 | "quotemark": [true, "single"], 52 | "radix": true, 53 | 54 | "semicolon": [true, "always", "ignore-bound-class-methods"], 55 | "trailing-comma": [true, { "singleline": "ignore" }], 56 | "triple-equals": [true, "allow-null-check"], 57 | "typedef-whitespace": [ 58 | true, 59 | { 60 | "call-signature": "nospace", 61 | "index-signature": "nospace", 62 | "parameter": "nospace", 63 | "property-declaration": "nospace", 64 | "variable-declaration": "nospace" 65 | } 66 | ], 67 | "unified-signatures": true, 68 | "variable-name": false, 69 | "whitespace": [ 70 | true, 71 | "check-branch", 72 | "check-decl", 73 | "check-operator", 74 | "check-separator", 75 | "check-type" 76 | ] 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /webpack.config.js: -------------------------------------------------------------------------------- 1 | const DtsBundleWebpack = require('dts-bundle-webpack') 2 | module.exports = { 3 | entry: './src/queryBuilder.ts', 4 | output: { 5 | filename: 'index.js', 6 | libraryTarget: 'umd' 7 | }, 8 | 9 | // Enable sourcemaps for debugging webpack's output. 10 | devtool: 'source-map', 11 | 12 | resolve: { 13 | // Add '.ts' and '.tsx' as resolvable extensions. 14 | extensions: ['.webpack.js', '.web.js', '.ts', '.tsx', '.js'] 15 | }, 16 | 17 | module: { 18 | rules: [ 19 | { test: /\.tsx?$/, use: [{ loader: 'awesome-typescript-loader' }] }, 20 | { 21 | enforce: 'pre', 22 | test: /\.js$/, 23 | use: [{ loader: 'source-map-loader' }], 24 | exclude: /(node_modules)/ 25 | } 26 | ] 27 | 28 | }, 29 | plugins: [ 30 | new DtsBundleWebpack({ 31 | name: 'QueryBuilder', 32 | main: 'dist/**/*.d.ts', 33 | out: 'index.d.ts', 34 | removeSource: true, 35 | outputAsModuleFolder: true, 36 | }) 37 | ], 38 | optimization: { 39 | // We no not want to minimize our code. 40 | minimize: true 41 | } 42 | }; --------------------------------------------------------------------------------