All Projects → lookinlab → Adonis Lucid Filter

lookinlab / Adonis Lucid Filter

Addon for filtering AdonisJS Lucid ORM

Programming Languages

typescript
32286 projects

Labels

Projects that are alternatives of or similar to Adonis Lucid Filter

adonis-sail
⛵Generate a ready-to-use local docker environment for your Adonis application
Stars: ✭ 36 (-46.27%)
Mutual labels:  adonisjs
adonis-tasks
A simple task list
Stars: ✭ 12 (-82.09%)
Mutual labels:  adonisjs
Bj Decoupage Territorial
API pour récupérer les départements, communes, arrondissements et les quartiers du Bénin
Stars: ✭ 29 (-56.72%)
Mutual labels:  adonisjs
adonis-cache
Cache provider for AdonisJS framework
Stars: ✭ 66 (-1.49%)
Mutual labels:  adonisjs
adonis-graphql-server
A GraphQL server built with Apollo server and AdonisJs
Stars: ✭ 31 (-53.73%)
Mutual labels:  adonisjs
Adonuxt Template
[Deprecated] Starter template for Nuxt.js with AdonisJS.
Stars: ✭ 457 (+582.09%)
Mutual labels:  adonisjs
adonisjs-laravel-mix
An AdonisJs fullstack application blueprint with Laravel Mix
Stars: ✭ 17 (-74.63%)
Mutual labels:  adonisjs
Adonis pro
node.js 框架 adonisjs WEB应用:多人在线文章分享平台
Stars: ✭ 52 (-22.39%)
Mutual labels:  adonisjs
adonis-recaptcha2
Google reCAPTCHA for AdonisJS
Stars: ✭ 24 (-64.18%)
Mutual labels:  adonisjs
Adminify
An Admin Dashboard based on Vuetify material
Stars: ✭ 923 (+1277.61%)
Mutual labels:  adonisjs
adonisjs-electron
Boilerplate for adonisjs + Electron
Stars: ✭ 17 (-74.63%)
Mutual labels:  adonisjs
manager
The builder (Manager) pattern implementation used by AdonisJs
Stars: ✭ 14 (-79.1%)
Mutual labels:  adonisjs
Rest Admin
Restful Admin Dashboard Based on Vue and Boostrap 4
Stars: ✭ 565 (+743.28%)
Mutual labels:  adonisjs
assembler
Set of commands to build and serve AdonisJS projects, along with `make:` commands
Stars: ✭ 25 (-62.69%)
Mutual labels:  adonisjs
Adonisdocbr
Documentação completa em português brasileiro da versão 4.1 do Adonisjs
Stars: ✭ 33 (-50.75%)
Mutual labels:  adonisjs
server
👨🏾‍🍳 Server for Ferdi that you can re-use to run your own
Stars: ✭ 26 (-61.19%)
Mutual labels:  adonisjs
Adonis App
Application structure for new adonis app, think of it as scaffolding a new project
Stars: ✭ 368 (+449.25%)
Mutual labels:  adonisjs
Create Adonis Ts App
Boilerplate to create a new AdonisJs typescript project
Stars: ✭ 63 (-5.97%)
Mutual labels:  adonisjs
Docs
AdonisJs Chinese Documentions
Stars: ✭ 46 (-31.34%)
Mutual labels:  adonisjs
Adonis Tdd Tutorial Demo
Stars: ✭ 22 (-67.16%)
Mutual labels:  adonisjs

Adonis Lucid Filter

Version for Adonis v4

Greenkeeper badge Build Status Coverage Status

Works with @adonisjs/[email protected] (^10..)

This addon adds the functionality to filter Lucid Models

Inspired by EloquentFilter

Introduction

Example, we want to return a list of users filtered by multiple parameters. When we navigate to:

/users?name=Tony&last_name=&company_id=2&industry=5

request.all() or request.get() will return:

{
  "name": "Tony",
  "last_name": "",
  "company_id": 2,
  "industry": 5
}

To filter by all those parameters we would need to do something like:

import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import User from 'App/Models/User'

export default class UserController {

  public async index ({ request }: HttpContextContract): Promise<User[]> {
    const { company_id, last_name, name, industry } = request.get()
  
    const query = User.query().where('company_id', +company_id)

    if (last_name) {
      query.where('last_name', 'LIKE', `%${last_name}%`)
    }
    if (name) {
      query.where(function () {
        this.where('first_name', 'LIKE', `%${name}%`)
          .orWhere('last_name', 'LIKE', `%${name}%`)
      })
    }

    return query.exec()
  }

}

To filter that same input with Lucid Filters:

import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import User from 'App/Models/User'

export default class UserController {

  public async index ({ request }: HttpContextContract): Promise<User[]> {
    return User.filter(request.all()).exec()
  }
}

Installation

Make sure to install it using npm or yarn.

# npm
npm i [email protected]
node ace invoke adonis-lucid-filter

# yarn
yarn add [email protected]
node ace invoke adonis-lucid-filter

Usage

Make sure to register the provider inside .adonisrc.json file.

{
  "providers": [
    "...other packages",
    "adonis-lucid-filter"
  ] 
}

For TypeScript projects add to tsconfig.json file:

{
  "compilerOptions": {
    "types": [
      "...other packages",
      "adonis-lucid-filter"
    ]
  } 
}

Generating The Filter

Only available if you have added adonis-lucid-filter/build/commands in commands array in your `.adonisrc.json'

You can create a model filter with the following ace command:

node ace make:filter User // or UserFilter

Where User is the Lucid Model you are creating the filter for. This will create app/Models/Filters/UserFilter.js

Defining The Filter Logic

Define the filter logic based on the camel cased input key passed to the filter() method.

  • Empty strings are ignored
  • setup() will be called regardless of input
  • _id is dropped from the end of the input to define the method so filtering user_id would use the user() method
  • Input without a corresponding filter method are ignored
  • The value of the key is injected into the method
  • All values are accessible through the this.$input a property
  • All QueryBuilder methods are accessible in this.$query object in the model filter class.

To define methods for the following input:

{
  "company_id": 5,
  "name": "Tony",
  "mobile_phone": "888555"
}

You would use the following methods:

import { BaseModelFilter } from '@ioc:Adonis/Addons/LucidFilter'
import { ModelQueryBuilderContract } from '@ioc:Adonis/Core/Lucid'
import User from 'App/Models/User'

export default class UserFilter extends BaseModelFilter {
  public $query: ModelQueryBuilderContract<typeof User, User>
  
  public static blacklist: string[] = ['secretMethod']

  // This will filter 'company_id' OR 'company'
  company (id: number) {
    this.$query.where('company_id', id)
  }

  name (name: string) {
    this.$query.where((builder) => {
      builder
        .where('first_name', 'LIKE', `%${name}%`)
        .orWhere('last_name', 'LIKE', `%${name}%`)
    })
  }

  mobilePhone (phone: string) {
    this.$query.where('mobile_phone', 'LIKE', `${phone}%`)
  }

  secretMethod (secretParameter: any) {
    this.$query.where('some_column', true)
  }
}

Blacklist

Any methods defined in the blacklist array will not be called by the filter. Those methods are normally used for internal filter logic.

The whitelistMethod() methods can be used to dynamically blacklist methods.

Example:

setup ($query) {
  this.whitelistMethod('secretMethod')
  this.$query.where('is_admin', true)
}

setup() not may be async

Note: All methods inside setup() will be called every time filter() is called on the model

In the example above secretMethod() will not be called, even if there is a secret_method key in the input object. In order to call this method it would need to be whitelisted dynamically:

Static properties

export default class UserFilter extends BaseModelFilter {
  // Blacklisted methods
  public static blacklist: string[] = []
  
  // Dropped `_id` from the end of the input
  // Doing this would allow you to have a `company()` filter method as well as a `companyId()` filter method.
  public static dropId: boolean = true
  
  // Doing this would allow you to have a mobile_phone() filter method instead of mobilePhone().
  // By default, mobilePhone() filter method can be called thanks to one of the following input key: mobile_phone, mobilePhone, mobile_phone_id
  public static camelCase: boolean = true
}

Applying The Filter To A Model

import UserFilter from 'App/Models/Filters/UserFilter'
import { filterable } from '@ioc:Adonis/Addons/LucidFilter'

@filterable(UserFilter)
export default class User extends BaseModel {
  // ...columns and props
}

This gives you access to the filter() method that accepts an object of input:

import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import User from 'App/Models/User'

export default class UserController {

  public async index ({ request }: HttpContextContract): Promise<User[]> {
    return User.filter(request.all()).exec()
  }

  // or with paginate method

  public async index ({ request }: HttpContextContract): Promise<SimplePaginatorContract<User>> {
    const { page = 1, ...input } = request.all()
    
    return User.filter(input).paginate(page, 15)
  }
}

Dynamic Filters

You can define the filter dynamically by passing the filter to use as the second parameter of the filter() method. Defining a filter dynamically will take precedent over any other filters defined for the model.

import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import AdminFilter from 'App/Models/Filters/AdminFilter'
import UserFilter from 'App/Models/Filters/UserFilter'

export default class UserController {

  public async index ({ request, auth }: HttpContextContract): Promise<User[]> {
    const Filter = auth.user.isAdmin() ? AdminFilter : UserFilter

    return User.filter(request.all(), Filter).exec()
  } 
}

Filtering relations (version >= 2.1)

For filtering relations of model may be use scope filtration, example:

import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import User from 'App/Models/User'

export default class UserPostsController {
  /**
   * Get a list posts of user
   * GET /users/:user_id/posts
   */
  public async index ({ params, request }: HttpContextContract): Promise<Post[]> {
    const user: User = await User.findOrFail(params.user_id)

    return user.related('posts').query()
      .apply(scopes => scopes.filtration(request.all()))
      .exec()
  }
}

Documentation Query Scopes

Note: At relation model must have defined Filter through decorator @filterable()

Thanks for the stars! ⭐️

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].