listing-query-manager
v1.2.0
Published
This utility allows you to handle repetitive tasks related to fetching data for listing: state management, url parsing, validation.
Downloads
5
Readme
Listing Query Manager
This utility allows you to handle repetitive tasks related to fetching data for listing: state management, url parsing, validation. It keeps state in url, and transforms it to two additional formats:
- Url - pretty and customizable formating e.g.
/my-listing?sort=created-desc&name=Donald%20T
- Params - ready to pass as argument to server call. Only allowed fields will pass e.g.
MyQuery.toQuery();
// => {
// sort: 'created-desc',
// filter: {
// name: 'Donald T'
// }
// }
- Mongo query - ready to pass to mongo find(). Define your default regex pattern once and use it across whole project e.g.
MyQuery.toMongo();
// => {
// sort: {
// createdAt: -1
// },
// filter: {
// name: {$regex: `^.*Donald T.*$`}
// }
// }
Usage
import {QueryManager} from 'listing-query-manager';
// client and server: Define query
const ItemsQuery = QueryManager.define({
filter: {
title: 'regex',
authorId: 'eq'
},
sort: {
created: 'createdAt',
title: 'title',
}
});
// client: subscribe and get data
Meteor.subscribe('items', {
query: ItemsQuery.toQuery()
}, function () {
const {filter, sort} = ItemsQuery.toMongo();
Items.find(filter, {sort});
});
// server: get data
Meteor.publish('items', function ({query}) {
const {filter, sort} = ItemsQuery.toMongo({query});
Items.find(filter, {sort});
return cursor;
});
// client: handle sorting by render clickable labels
class Listing extends React.Component {
render () {
return (
<ClickToSort name="name" queryParams={queryParams}>
Name
</ClickToSort>
<ClickToSort name="createdAt" queryParams={queryParams}>
Created At
</ClickToSort>
);
}
}
// client: handle filtering
ItemsQuery.setFilter({
name: 'Donald T'
});
API
// long form
Listing.define({
filter: {
name: ({name, value}) => {
return {
name: {$regex: `^.*${value}.*$`}
}
},
itemId: ({name, value}) => {
return {
itemId: value
}
}
},
sort: {
created: 'createdAt',
title: 'title',
}
});