query-builder-odata builds OData v4 queries.
yarn add query-builder-odata
or
npm install --save query-builder-odata
import { QueryBuilder } from 'query-builder-odata';
const query = new QueryBuilder()
.top(10)
.skip(10)
.count()
.select('name')
.orderBy('name')
.expand('Books', e => e.select('title'))
.filter(f => f.eq('name', 'John Doe'))
.toQuery();
query => "?$top=10&$skip=10&$count=true&$select=name&$orderby=name&$expand=Books($select=title)&$filter=name eq 'John Doe'"
const query = new QueryBuilder()
.top(10)
.toQuery();
query => "?$top=10"
const query = new QueryBuilder()
.skip(10)
.toQuery();
query => "?$skip=10"
const query = new QueryBuilder()
.count()
.toQuery();
query => "?$count=true"
const query = new QueryBuilder()
.select('id', 'name')
.toQuery();
query => "?$select=id,name"
const query = new QueryBuilder()
.orderBy('id desc' ,'name')
.toQuery();
query => "?$orderBy=id desc,name"
const query = new QueryBuilder()
.expand('Books')
.toQuery();
query => "?$expand=Books"
const query = new QueryBuilder()
.expand('Books', e =>
e.expand('Chapters')
)
.toQuery();
query => "?$expand=Books($expand=Chapters)"
Expand can be used together with top, skip, count, select, orderBy, filter
const query = new QueryBuilder()
.expand('Books', e => e
.select('title')
.orderBy('isbn')
)
.toQuery();
query => "?$expand=Books($select=title;$orderBy=isbn)"
const query = new QueryBuilder()
.filter(f => f.eq('name', 'John Doe'))
.toQuery();
query => "?$filter=name eq 'John Doe'"
Supported operators:
eq, ne, gt, ge, lt, le, in
startswith, endswith, contains
When using multiple operators, the logical and
operator is used by default.
const query = new QueryBuilder()
.filter(f => f
.startsWith('name', 'John')
.gt('rating', 5)
)
.toQuery();
query => "?$filter=startswith(name, 'John') and rating gt 5"
Supported operators: and, or
const query = new QueryBuilder()
.filter(f =>
f.or(o => o
.startsWith('name', 'John')
.gt('rating', 5)
)
)
.toQuery();
query => "?$filter=startswith(name, 'John') or rating gt 5"
When adding multiple query operators of the same type, one of two scenarios will happen: overriding or addition.
The following operators will override the existing value: top, skip, count
const query = new QueryBuilder()
.top(10)
.top(15)
.toQuery();
query => "?$top=15"
The following operators will add to the existing value: select, orderBy, expand, filter
const query = new QueryBuilder()
.select('name')
.select('age')
.toQuery();
query => "?$select=name,age"
More examples can be found in the tests.