1.2.1 • Published 4 years ago

knex-json-where v1.2.1

Weekly downloads
1
License
BSD-3-Clause
Repository
github
Last release
4 years ago

knex-json-where

Add filters on Knex query through a JSON object.

Great for use with REST or GraphQL APIs that need filtering on requests

Install

npm i knex-json-where@latest --save

Import

import { jsonWhere } from 'knex-json-where';

Example

JSON filters

const json = {
   id: {
      _eq: 1 // id equal 1
   },
   birth_date: {
      _isnull: false // and birth_date is not null (true for 'is null')
   },
   _or: {
      name: {
         _lk: "ana%" // or name like ana
      },
      created_at: {
         _gte: "2019-01-01 00:00:00" // and created_at is greater or equal to 2019-01-01 00:00:00
      },
      _or: {
         name: {
            _lk: "luis%" // or name like luis
         },
         created_at: {
            _gte: "2019-02-01 00:00:00" // and created_at is greater or equal to 2019-02-01 00:00:00
         }
      }
   }
}

Knex query

const query = knex('users')
   .select('id', 'name')
   .where(jsonWhere(json));

Result

select id, name 
from users 
where (id = 1 or (name like 'ana%' and created_at >= '2019-01-01 00:00:00' or (name like 'luis%' and created_at >= '2019-02-01 00:00:00')))

Operators

OperatorDescription
_eqequals
_neqnot equals
_gtgreater than
_gtegreater than or equal to
_ltless than
_lteless than or equal to
_inin
_ninnot in
_lklike
_nlknot like
_ilkilike (PostgreSQL only)
_inlknot ilike (PostgreSQL only)
_isnullis null - is not null
_oror

Additional Information

  • The operator _or can only be used at the field level.

  • If you are using PostgreSQL, consider using citext instead of text, because citext is not case sensitive when using the _lk or _nlk operator, or use ilk and inlk

1.2.1

4 years ago

1.1.1

4 years ago

1.1.0

4 years ago

1.0.0

4 years ago

0.1.1

4 years ago

0.1.0

4 years ago