import camelCase from 'lodash/camelCase' ; import { LucidFilter , LucidFilterContract } from '@ioc:Adonis/Addons/LucidFilter' ; import { LucidModel , LucidRow , ModelQueryBuilderContract } from '@ioc:Adonis/Lucid/Orm' ; function StaticImplements < T > ( ) { return ( _t ) => { } ; } class constructor @ StaticImplements < LucidFilterContract > ( ) export class BaseModelFilter implements LucidFilter { public [ 'constructor' ] : typeof BaseModelFilter ; public static blacklist : string [ ] = [ ] ; public static dropId : boolean = true ; public static camelCase : boolean = true ; public setup ? ( $query ) ; public $blacklist : string [ ] ; constructor ( public $query , public $input ) { this . $input = BaseModelFilter . removeEmptyInput ( this . $input ) ; this . $blacklist = this . constructor . blacklist ; } public handle ( ) { if ( this . setup && typeof this . setup === 'function' ) { this . setup ( this . $query ) ; } this . $filterByInput ( ) ; return this . $query ; } public whitelistMethod ( method ) { const index = this . $blacklist . indexOf ( method ) ; if ( ~ index ) { this . $blacklist . splice ( index , 1 ) ; } return ! ! ~ index ; } public $filterByInput ( ) { for ( const key in this . $input ) { const method = this . $getFilterMethod ( key ) ; const value = this . $input [ key ] ; if ( this . $methodIsCallable ( method ) ) { this [ method ] ( value ) ; } } } public $getFilterMethod ( key ) { const methodName = this . constructor . dropId ? key . replace ( /^(.*)(_id|Id)$/ , '$1' ) : key ; return this . constructor . camelCase ? camelCase ( methodName ) : methodName ; } public static removeEmptyInput ( input ) { const filteredInput = { } ; for ( let key in input ) { const value = input [ key ] ; if ( value !== '' && value !== null && value !== undefined ) { filteredInput [ key ] = value ; } } return filteredInput ; } public $methodIsCallable ( method ) { return ! ! this [ method ] && typeof this [ method ] === 'function' && ! this . $methodIsBlacklisted ( method ) ; } public $methodIsBlacklisted ( method ) { return this . $blacklist . includes ( method ) ; } } export default BaseModelFilter ;