ts-odata-filter
A typescript library for buiding OData filter string
Install
npm install ts-odata-filter --save
Usage
Basic usage
import { ODataFilterBuilder, BuilderFunc, BoolArg } from 'ts-odata-filter'
interface IEntity {
id: number
}
interface IProduct extends IEntity {
name: string
description: string
price: number
}
interface IOrderItem extends IEntity {
product: IProduct
quantity: number
price: number
parentOrder: IOrder
}
interface IOrder extends IEntity {
customer: ICustomer
status: 'CREATED' | 'PAID' | 'CANCELLED'
createdDate: Date
orderItems: IOrderItem[]
}
interface ICustomer extends IEntity {
name: string
}
ODataFilterBuilder.build<IOrder>(builder => builder.eq(builder.prop.customer.id, 123)).getString();
ODataFilterBuilder.build<IOrder>(
builder => builder.eq(builder.prop.someProperty, 123)
).getString();
ODataFilterBuilder.build<IOrder>(
builder => builder.eq(builder.prop.customer.id, '123')
).getString();
const filter: BuilderFunc<IOrder> = (b, p) =>
b.and(
b.eq(p.customer.id, 123),
b.eq(p.status, 'PAID')
);
ODataFilterBuilder.build<IOrder>(filter).getString();
Destructuring builder argument
const filter: BuilderFunc<IOrder> = ({eq, and}, p) =>
and(
eq(p.customer.id, 123),
eq(p.status, 'PAID')
);
ODataFilterBuilder.build(filter).getString();
Working with collections
const filter: BuilderFunc<IOrder> = (b, p) =>
b.collection(p.orderItems, 'i').any(
i => i.contains(i.prop.product.name, 'IPhone')
);
ODataFilterBuilder.build(filter).getString();
Reusing filter expressions
const filterIphones: BoolFunc<IProduct> = (b, p) =>
b.or(
b.contains(p.name, 'IPhone'),
b.contains(p.description, 'IPhone')
);
ODataFilterBuilder.build(filterIphones).getString();
const filterOrderItems: BoolFunc<IOrderItem> = (b, p) =>
b.and(
b.nested(p.product, filterIphones),
b.gt(p.price, 1000)
);
ODataFilterBuilder.build(filterIphones).getString();
const filterOrders: BoolFunc<IOrder> = (b, p) =>
b.and(
b.collection(p.orderItems, 'i').any(filterOrderItems),
b.contains(p.customer.name, 'John')
);
ODataFilterBuilder.build(filterOrders).getString();