objection-data-provider

Wrapper finder for objection

Usage no npm install needed!

<script type="module">
  import objectionDataProvider from 'https://cdn.skypack.dev/objection-data-provider';
</script>

README

Objection Data Provider

Wrapper finder for objection

Instalation

npm i @xyluet/objection-data-provider

Usage

Basic usage

Currently we have 3 major methods to get the results:

  • results() to get the result.
  • totalCount() basically count the query passed to dataProvider.
  • filteredCount() when using filter, you can get count the filtered data.
const dataProvider = require(`objection-data-provider`);

(async () => {
  const query = Model.query();
  const finder = dataProvider(query).build(ctx.request.query) // the request object
  const data = await finder.results();
  const totalCount = await finder.totalCount();
  const filteredCount = await finder.filteredCount();
})();

Request example

{
  sort: `name,-age`, // order by name asc and age desc
  page: 2, // change to page 2
  size: 5, // each request will only get 5 data
  filter: `name:like=%F%;age:gt=20` // name like %F% and age >= 20
}

It will throw error if the column doesn't exists in database. All builder will try to use objection propertyNameToColumnName() method to get the column name if you use columnNameMappers().

Current best way is using try catch.

Advanced usage

const options = {
  // set to false to disable pagination
  pagination: {
    defaultPageSize: 15, // default 10
    pageParam: `pages`, // default `page`
    pageSizeParam: `per`, // default `size`
  },
  // set to false to disable sort
  sort: {
    sortParam: `order`, // default `sort`
  },
  // set to false to disable sort
  filter: {
    filterParam: `fields`, // default `filter`
  },
};
const finder = (
  dataProvider(query)
    .options(options)
    .build(ctx.request.query)
);

Filter

Current available expression:

  • eq
  • like
  • ne
  • gt
  • lt
  • gte
  • lte
  • in

default to eq if you not specify the express, e.g. name=foo.

All filter value will be split first by separator ; > trimLeft > ignore if expression not implemented.

Sort

  • For asc use regular name like name.
  • For desc use prefix - like -name.

Pagination

  • Page is MUST not be lower than 1 or not a string, otherwise it will converted to 1.
  • Page size can't be higher than defaultPageSize or will converted to defaultPageSize.
  • page size can't be lower than 1 or will converted to 1.

Todo