Skip to content
Permalink
Browse files
fix(knex): add ability to filter by null state
  • Loading branch information
Enda Phelan committed Sep 21, 2020
1 parent 5143fb6 commit d10e918714a85c8c6f6ebb4260e9aff0b6b99ffa
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
@@ -1,7 +1,7 @@
import Knex from 'knex';
import { QueryFilter, QueryFilterOperator } from '@graphback/core';

const knexOperators = ['=', '<>', '<=', '<', '>', '>=', 'like', 'between', 'in'] as const;
const knexOperators = ['=', '<>', '<=', '<', '>', '>=', 'like', 'between', 'in', 'is', 'is not'] as const;
const knexMethods = ['where', 'orWhere', 'orWhereNot', 'whereNot'] as const;

type KnexQueryOperator = typeof knexOperators[number];
@@ -29,8 +29,10 @@ export interface CRUDKnexQueryMapper {

const mapQueryFilterOperatorToKnexWhereCondition = (operator: QueryFilterOperator, value: any): KnexWhereConditionMap => {
const operatorToWhereConditionMap: { [key in QueryFilterOperator]: KnexWhereConditionMap } = {
eq: ['=', value],
ne: ['<>', value],
// eslint-disable-next-line no-null/no-null
eq: [value === null ? 'is' : '=', value],
// eslint-disable-next-line no-null/no-null
ne: [value === null ? 'is not' : '<>', value],
lt: ['<', value],
le: ['<=', value],
ge: ['>=', value],
@@ -31,6 +31,28 @@ describe('knexQueryMapper', () => {
expect(queryBuilder.buildQuery(filter).toQuery()).toEqual("select * where (`name` = 'Enda')")
});

test('where name is null', () => {
const filter: QueryFilter = {
name: {
// eslint-disable-next-line no-null/no-null
eq: null
}
}

expect(queryBuilder.buildQuery(filter).toQuery()).toEqual("select * where (`name` is null)")
})

test('where name is not null', () => {
const filter: QueryFilter = {
name: {
// eslint-disable-next-line no-null/no-null
ne: null
}
}

expect(queryBuilder.buildQuery(filter).toQuery()).toEqual("select * where (`name` is not null)")
})

test('where name <> ?', () => {
const filter: QueryFilter = {
name: {

0 comments on commit d10e918

Please sign in to comment.