Code Monkey home page Code Monkey logo

adonis-lucid-filter's People

Contributors

greenkeeper[bot] avatar lookingit avatar maximemrf avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

adonis-lucid-filter's Issues

Is it working with latest @adonisjs/lucid v18.3.0?

I am using adonis-lucid-filter v4.1.0 and when a try to:

User.filter(filterData).paginate(page, 10);

i am getting this error:

{
    "message": "Cannot read properties of undefined (reading 'paginate')",
    "stack": "TypeError: Cannot read properties of undefined (reading 'paginate')\n    at UsersController.index (/home/node/app/app/Controllers/Http/Admin/UsersController.ts:22:26)\n    at processTicksAndRejections (node:internal/process/task_queues:96:5)\n    at Object.PreCompiler.runRouteHandler [as fn] (/home/node/app/node_modules/@adonisjs/http-server/build/src/Server/PreCompiler/index.js:47:31)\n    at AuthMiddleware.handle (/home/node/app/app/Middleware/Auth.ts:76:5)\n    at Server.handleRequest (/home/node/app/node_modules/@adonisjs/http-server/build/src/Server/index.js:108:13)"
}

User Model is extending from compose(BaseModel, Filterable) and have the public static $filter = () => UserFilter

User.query().paginate(page, 10) works.

Action required: Greenkeeper could not be activated 🚨

🚨 You need to enable Continuous Integration on all branches of this repository. 🚨

To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because it uses your CI build statuses to figure out when to notify you about breaking changes.

Since we didn’t receive a CI status on the greenkeeper/initial branch, it’s possible that you don’t have CI set up yet. We recommend using Travis CI, but Greenkeeper will work with every other CI service as well.

If you have already set up a CI for this repository, you might need to check how it’s configured. Make sure it is set to run on all new branches. If you don’t want it to run on absolutely every branch, you can whitelist branches starting with greenkeeper/.

Once you have installed and configured CI on this repository correctly, you’ll need to re-trigger Greenkeeper’s initial pull request. To do this, please delete the greenkeeper/initial branch in this repository, and then remove and re-add this repository to the Greenkeeper App’s white list on Github. You'll find this list on your repo or organization’s settings page, under Installed GitHub Apps.

Global filters

I have a requirement where filters are sent in this format filter[field]&filter[anotherfield]&etc...
and i created a filter for the User model in adonisJS v5

export default class UserFilter extends BaseModelFilter {
  public $query: ModelQueryBuilderContract<typeof User, User>;

  //"filter":{"email":"","firstname":"","fullname":"a"},"sort":["name,asc","id,desc"]}

  public filter(values: any) {
    Object.keys(values).map((key) => {
      this.$query.where(key, "LIKE", `%${values[key]}%`);
    });
  }

  public sort(values) {
    if (typeof values === "string") {
      const [col, order] = values.split(",");
      this.$query.orderBy(col, order);
    }

    if (typeof values === "object") {
      values.forEach((element) => {
        const [col, order] = element.split(",");
        this.$query.orderBy(col, order);
      });
    }
  }
}

This works great
but i dont want to repeat this class for every single model in my app
How can i then make this class a "Generic" one and pass the model as a constructor

I was thinking something like this

controller.js

 public async index({ request }: HttpContextContract) {
    const { page = 1, size = 10, ...rest } = request.qs();
    const users = await GenericFilter<User>.filter(rest).paginate(page, size);
  //OR
    const users = await GenericFilter.filter(User, rest).paginate(page, size);
    return users;
  }

The implementation of the filter would have to follow one of the two cases
Also there is the case that maybe i complicated the issue and there is a easy way .. Anyway thanks

Filter pattern

I came across this package while searching for an equivalent migration from Laravel.
Laravel-Query-Builder from Spatie supports URL filters by adding ?filter[name]=John. How can I configure the package this way, so I could keep the existing URL structure?

[Solved]methods that contain Id doesn't seem to work.

So I have this method inside my filter.js

    accountId(accountId){
        return this.where('account_id', accountId)
    }

for some reason the method isn't called if account_id param is present.

but if I pass account_i or account param and change the method name to accountI or account the filter works fine.

Async support in `setup` and `filter method`s

Hi @LookinGit.

In my use case for Adonis Lucid Filter, there are need for supporting async setup and filter methods. What is the possibility of this being supported?

I've looked at the BaseModel and Mixin and it looks feasible. Or are there other reasons for not supporting async operations?

This an example of an async operation within a filter method:

  public async enterprises(ids?: string | string[]) {
    const relatedWorkspaces = await Workspace.query()
      .whereIn('workspaces.enterprise_id', this.getIds(ids))
      .select('id')

    this.$query.whereIn(
      'brands.workspace_id',
      relatedWorkspaces.map((workspace) => workspace.id)
    )
  }

I spent 2 days wondering while that particular method was not filtering properly while others work as expected. Until I realised that async method might not be supported by the plugin. 😂

V5 relatioship query

In v4 you could have relationship constraints like:

    type(type){
        return this.related('profile', 'type', type)
    }

What is the equivalent in v5 lucid filter?

Relationship based filtering

Hi, first of all I just want to say this is a good module to easily filter data.

I have a question, how can you do something like this:

const { training, participants, start_date } = request.get();

let q = Schedule.query();

if (training === 'true') {
  q = q.with('speakers');
}

if (participants === 'true') {
  q = q.with('speakers');
}

if (start_date) {
  q = q.where('start_date', '>=', start_date)
}

await q.fetch();

Basically what it does is when those params exist, it gets the related items. I checked the documentation and I only see a simple usage of relationship using the with method.

Is it something you can also do with this module? Thanks in advance.

Critical bug: values are being cached

There are some issues when fitlering with the filter method, for ex:

import { BaseModelFilter } from '@ioc:Adonis/Addons/LucidFilter'
import { ModelQueryBuilderContract } from '@ioc:Adonis/Lucid/Orm'
import Balance from 'App/Modules/Balance/Models/Balance.Model'

export default class BalanceFilter extends BaseModelFilter {
  public $query: ModelQueryBuilderContract<typeof Balance, Balance>

  public static camelCase: boolean = false

  id(id: string) {
    this.$query.where({ id })
  }

  accountId(accountId: string) {
    this.$query.where({ accountId })
  }
}
      console.log('----')
      console.log(accountId)
      const [debitBalance, creditBalance] = await Promise.all([
        Balance.filter({
          accountId,
          currency: 'foo'
        })
          .first(),
        Balance.filter({
          accountId,
          currency:  'bar'
        }).first(),
      ])
      console.log('debit account id', debitBalance?.accountId)
      console.log('----')

will give the following output when sending 2 requests with different account ids:

----
a5a93a1c-44f1-4091-a81a-9bb5053d4a10
debit account id a5a93a1c-44f1-4091-a81a-9bb5053d4a10
----
----
7db9f581-cea3-4a66-851a-2709ebe71ac6
debit account id a5a93a1c-44f1-4091-a81a-9bb5053d4a10
----

which is obvousily wrong, if I remove the filter method on Balance class and add .query() and the .wheres conditions it works propery

----
946ccbe9-2df5-4960-aa12-195bedfd33cd
debit account id 946ccbe9-2df5-4960-aa12-195bedfd33cd
----
----
70d83ce8-c48a-491c-8164-b0b27d6ecb63
debit account id 70d83ce8-c48a-491c-8164-b0b27d6ecb63
----

any ideas?

filter seems not working when combined with wherehas

im not sure this is an issue or something else.

my code something looks like this

........
const query = this.model.query()
query.whereHas('escalations', (builder) => {
    builder.whereIn('to_level', [2])
})
query.filter(params.filter)`
return query.paginate()
.........

the filter seems to be ignored (not working as expected) when there is a whereHas()

but when i remove/comment the whereHas() query part, everything filtered as expected.

maybe someone has any idea what's going on?

Order By change ? Default value ?

Hello,
I use adonisJS 6, I installed the library to manage my filters which is very practical. Thanks for that.

However, I've noticed that using a filter on my model changes the sort in which I receive my data.

I have several questions: is it normal for the sorting to change? Have I made a configuration error?
And can I apply a default sorting filter to all the models and then put an orderBy on each of the queries?

Currently, I've created a filter that adds a like on a text field, very simple and I've added the import of this filter in my model to use the .filter in my controller.

Sorry if there's any documentation on this, I haven't found any information on this.
Thanks in advance.

Filtering relationships with 'OR'

Hello, I'm trying to make a filter using 'this.related' but I needed it to bring records using 'OR' instead of 'AND' ... how can I do it?

It would be something like this:

builder.orWhere(x.field, 'LIKE', %${x.value}%)

.related() queries can't use the filter method

If I am trying to query based on related relationships and I get an ts error:

Property 'filter' does not exist on type 'HasManyClientContract<HasManyRelationContract<LucidModel, typeof Account>, typeof Account>'.ts(2339)

and a runtime error:

params.user.related(...).filter is not a function

My code:

    const accounts = await user
      .related('accounts')
      .filter(params)
      .preload('profile')
      .orderBy('created_at', params.orderBy)
      .paginate(params.page, params.perPage)

using this code works as intended:

        const accounts = await Account
            .filter(params)
            .with('profile')
            .orderBy('created_at', params.order)
            .paginate(params.page, params.per_page)

but I have to specify userId in params, and I would like to be able to filter based on the user hasMany accounts relationship.

In v4 this could have been done like this:

        const accounts = await user
            .accounts()
            .filter(params)
            .with('profile')
            .orderBy('created_at', params.order)
            .paginate(params.page, params.per_page)

and it works.

Does anyone have any clue on how to achieve this ?

How to add check based on 2 fields.

Requirement :- There are two fields in filter 1) Holiday number, 2) Reading number(1 OR 2).
The filter is required to accept both the fields and make an AND condition of both using whereHas.

Problem :- I have holiday defined on filter like
holiday(holiday: number) { this.$query.whereHas('holidays', (query) => query.wherePivot('holidays_id', holiday)) }

How can I access reading number inside that ?
I tried using this.$input but typesciprt error is coming saying
readings does not exists on type object.
Thanks :)

Can't use filter in User model

For some reason the filter doesn't work in User model, the other models it works just fine.

I think it's not even passing through the filter functions defined in my UserFilter which extends ModelFilter, because if I put some console logs, it won't be executed.

My UserFilter:

const ModelFilter = use('ModelFilter')

class UserFilter extends ModelFilter {
    secure_id(secure_id) {
        return this.where('secure_id', secure_id)
    }

    full_name(full_name) {
        return this.where('full_name', full_name)
    }

    email(email) {
        return this.where('email', email)
    }

    type_doc(type_doc) {
        return this.where('type_doc', type_doc)
    }

    number_doc(number_doc) {
        return this.where('number_doc', number_doc)
    }

    cellphone(cellphone) {
        return this.where('cellphone', cellphone)
    }

    status(status) {
        return this.where('status', status)
    }

    status(role) {
        return this.where('role', role)
    }
}

module.exports = UserFilter

In the boot function inside my User model I'm adding the trait like that: this.addTrait('@provider:Filterable', UserFilter)

And finally in my UserService where I'm calling the filter function and I guarantee the filter is coming populated or I can just pass an object there and it won't work anyways:

static async getUsers(filter) {
    return (await User.query().filter(filter).fetch()).toJSON()
}

Filters with uppercase and underscores

I have this function at my PostFilter.ts

public authorId(authorId: string): void {
   this.$query.where('authorId', authorId)
}

It does not match the value to the this function, so if I pass the { authorId: 1 } as parameter it will not call this function, and if I use another name as author_id, does not work too.

I need to convert it to authorid, then it works.

Seems that function names need to be alphanumeric without uppercase letters.

Do not apply filter to query

I have executed all commands on readme page to run on Adonis 5.
Using this code :

  public async index({ request, response, logger }: HttpContextContract) {
    const { page = 1, perPage = 10, ...input } = request.qs()
    console.log(input)
    const partners = Partner.filter(input).paginate(page, perPage)
    logger.info({ Page: page, PerPage: perPage }, 'Partners search success')
    return response.ok(partners)
 }

This is the output log :

{ name: 'Claudio' } <<-- input
[1642161988635] INFO (pv-backend/17956 on ASUS): Partners search success
Page: 1
PerPage: 10

As you can see, the debugging query logger do not contain any where statement
"sqlite" Partner (3.7 ms) SELECT COUNT(*) AS total FROM partners []
"sqlite" Partner (2 ms) SELECT * FROM partners LIMIT ? [ 10 ]

Obviously, a partner with name Claudio exist on db, but any rows was not returned.

I'm missing any things ?

Thank's

An in-range update of nyc is breaking the build 🚨

The devDependency nyc was updated from 14.0.0 to 14.1.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

nyc is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).
  • coverage/coveralls: First build on greenkeeper/nyc-14.1.0 at 98.925% (Details).

Commits

The new version differs by 15 commits.

  • c5d90fa chore(release): 14.1.0
  • 5cc05f4 chore: Update dependencies
  • 1e39ae1 chore: Refresh snapshots, update test/config-override.js to use helpers (#1085)
  • 3d9eaa4 fix: Purge source-map cache before reporting if cache is disabled. (#1080)
  • 132a074 feat: Add support for env.NYC_CONFIG_OVERRIDE (#1077)
  • 6fc109f chore: node.js 12 compatibility for object snapshot test. (#1084)
  • a7bc7ae fix: Use correct config property for parser plugins (#1082)
  • 600c867 chore: Convert some tap tests to run parallel and use snapshots. (#1075)
  • 56591fa docs: instrument docs update [skip ci] (#1063)
  • ca84c42 docs(codecov): favour npx over installing locally [skip ci] (#1074)
  • 85c1eac chore: Add test for nyc --no-clean. (#1071)
  • 21fb2c8 fix: Exit with code 1 when nyc doesn't know what to do. (#1070)
  • 0f745ca chore: Use class to declare NYC (#1069)
  • ca37ffa feat: add support for yaml configuration file (#1054)
  • c4fcf5e fix: Do not crash when nyc is run inside itself. (#1068)

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

An in-range update of @adonisjs/ace is breaking the build 🚨

The devDependency @adonisjs/ace was updated from 5.0.5 to 5.0.6.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

@adonisjs/ace is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

Commits

The new version differs by 3 commits.

  • e8df485 Merge branch 'release/5.0.6'
  • 9b1c368 chore(release): 5.0.6
  • 0d8a61a chore(package): update dependencies

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

pagination not return the correct value after filtering

Hello,

I'm currently having a problem using pagination with this filter.
the total, perPage, page, and lastPage doesn't return the correct value after filtering. this is my source code

const products = await Product.query().filter(query).paginate(page, 12)

in my db it should return { total: 59, perPage: 12, page: '3', lastPage: 5, }

instead of { total: 400, perPage: 12, page: '3', lastPage: 34, }

here is my model filter code

async subcategory (name) {
    const categoryQuery = await ProductCategory.findByOrFail('slug', name)
    const categoryId = categoryQuery.id
    return this.where('category_id', categoryId)
}

Adonis Version: 4.1.0
Lucid Version: 5.0.4
Adonis Filter Version: 1.0.3

An in-range update of sqlite3 is breaking the build 🚨

The devDependency sqlite3 was updated from 4.0.6 to 4.0.7.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

sqlite3 is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build failed (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Adonis 5 installation help needed.

follow the steps to install lucid filter in adonis 5.

  1. yarn add adonis-lucid-filter@alpha

  2. node ace invoke adonis-lucid-filter
    update tsconfig.json { types += adonis-lucid-filter }
    update .adonisrc.json { commands += adonis-lucid-filter/build/commands }
    update .adonisrc.json { providers += adonis-lucid-filter }
    ✔ create ace-manifest.json

  3. node ace make:filter Transaction
    ✔ create app/Models/Filters/TransactionFilter.ts

open up TransactionFilter.ts,
it has error on the import statement:
import { BaseModelFilter } from '@IOC:Adonis/Addons/LucidFilter'

error shown:
Cannot find module '@IOC:Adonis/Addons/LucidFilter' or its corresponding type declarations.ts(2307)

Add deleted_at in where to link tables

Hi
When using preload, I think that deleted_at should be added to all tables involved.
For example, if a link between book and author is removed, the search will still bring the link, because the deleted_at is for the Book table, I think I should add it to the author_book table as well.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.