@codenameryuu/adonis-lucid-filter 3.1.0 → 3.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE.md CHANGED
@@ -1,9 +1,9 @@
1
- # The MIT License
2
-
3
- Copyright (c) 2024 Lookin Anton
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
-
7
- The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
-
9
- THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
1
+ # The MIT License
2
+
3
+ Copyright (c) 2026 Codename Ryuu
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -1,218 +1,218 @@
1
- # @codenameryuu/adonis-lucid-filter
2
-
3
- This addon adds the functionality to filter Lucid Models Adonis JS 7. Inspired by [EloquentFilter](https://github.com/Tucker-Eric/EloquentFilter)
4
-
5
- ## Requirement
6
-
7
- - Adonis Js 7
8
- - Lucid 22 or higher
9
-
10
- ## Installation
11
-
12
- - Install the package
13
-
14
- ```bash
15
- yarn add @codenameryuu/adonis-lucid-filter
16
- ```
17
-
18
- - Configure the package
19
-
20
- ```bash
21
- node ace configure @codenameryuu/adonis-lucid-filter
22
- ```
23
-
24
- - Make sure to register the provider inside `adonisrc.ts` file.
25
-
26
- ```typescript
27
- providers: [
28
- // ...
29
- () => import('@codenameryuu/adonis-lucid-filter/provider'),
30
- ],
31
- commands: [
32
- // ...
33
- () => import('@codenameryuu/adonis-lucid-filter/commands')
34
- ]
35
- ```
36
-
37
- ## Usage
38
-
39
- You can create a model filter with the following ace command:
40
-
41
- ```bash
42
- node ace make:filter product
43
- ```
44
-
45
- Where `product` is the Lucid Model you are creating the filter for. This will create `app/models/filters/product_filter.ts`
46
-
47
- ### Defining The Filter Logic
48
-
49
- Define the filter logic based on the camel cased input key passed to the `filter()` method.
50
-
51
- - Empty strings are ignored
52
- - `setup()` will be called regardless of input
53
- - `_id` is dropped from the end of the input to define the method so filtering `product_id` would use the `product()` method
54
- - Input without a corresponding filter method are ignored
55
- - The value of the key is injected into the method
56
- - All values are accessible through the `this.$input` a property
57
- - All QueryBuilder methods are accessible in `this.$query` object in the model filter class.
58
-
59
- To define methods for the following input:
60
-
61
- ```json
62
- {
63
- "productCategoryId": 1,
64
- "name": "Car",
65
- "price": 100000
66
- }
67
- ```
68
-
69
- You would use the following methods:
70
-
71
- ```typescript
72
- import { BaseModelFilter } from '@codenameryuu/adonis-lucid-filter'
73
- import type { ModelQueryBuilderContract } from '@adonisjs/lucid/types/model'
74
- import Product from '#models/product'
75
-
76
- export default class ProductFilter extends BaseModelFilter {
77
- declare $query: ModelQueryBuilderContract<typeof Product>
78
-
79
- // Blacklisted methods
80
- static blacklist: string[] = ['secretMethod']
81
-
82
- // Dropped `_id` from the end of the input
83
- // Doing this would allow you to have a `company()` filter method as well as a `companyId()` filter method.
84
- static dropId: boolean = true
85
-
86
- // Doing this would allow you to have a mobile_phone() filter method instead of mobilePhone().
87
- // By default, mobilePhone() filter method can be called thanks to one of the following input key:
88
- // mobile_phone, mobilePhone, mobile_phone_id, mobilePhoneId
89
- static camelCase: boolean = true
90
-
91
- // This will filter 'productCategoryId', 'product_category_id' OR 'productCategory'
92
- productCategory(id: number) {
93
- this.$query.where('product_category_id', id)
94
- }
95
-
96
- name(name: string) {
97
- this.$query.where('name', 'LIKE', `%${name}%`)
98
- }
99
-
100
- price(price: number) {
101
- this.$query.where('price', price)
102
- }
103
-
104
- secretMethod(secretParameter: any) {
105
- this.$query.where('some_column', true)
106
- }
107
- }
108
- ```
109
-
110
- #### Blacklist
111
-
112
- Any methods defined in the `blacklist` array will not be called by the filter.
113
- Those methods are normally used for internal filter logic.
114
-
115
- The `whitelistMethod()` methods can be used to dynamically blacklist methods.
116
-
117
- Example:
118
-
119
- ```typescript
120
- setup($query) {
121
- this.whitelistMethod('secretMethod')
122
- this.$query.where('is_admin', true)
123
- }
124
- ```
125
-
126
- > `setup()` not may be async
127
-
128
- > **Note:** All methods inside `setup()` will be called every time `filter()` is called on the model
129
-
130
- In the example above `secretMethod()` will not be called, even if there is a `secret_method` key in the input object.
131
- In order to call this method it would need to be whitelisted dynamically:
132
-
133
- ### Applying The Filter To A Model
134
-
135
- ```typescript
136
- import { compose } from '@adonisjs/core/helpers'
137
- import { Filterable } from '@codenameryuu/adonis-lucid-filter'
138
-
139
- import ProductFilter from '#models/filters/product_filter'
140
-
141
- export default class Product extends compose(BaseModel, Filterable) {
142
- static $filter = () => ProductFilter
143
-
144
- // ...columns and props
145
- }
146
- ```
147
-
148
- This gives you access to the `filter()` method that accepts an object of input:
149
-
150
- ```typescript
151
- import type { HttpContext } from '@adonisjs/core/http'
152
- import Product from '#models/product'
153
-
154
- export default class ProductsController {
155
- async index({ request }: HttpContext): Promise<Product[]> {
156
- return Product.filter(request.all()).orderBy('created_at', 'desc')
157
- }
158
-
159
- // or with paginate method
160
-
161
- async index({ request }: HttpContext): Promise<ModelPaginatorContract<Product>> {
162
- return Product.filter(request.all()).paginate(1, 10)
163
- }
164
- }
165
- ```
166
-
167
- ### Dynamic Filters
168
-
169
- You can define the filter dynamically by passing the filter to use as the second parameter of the filter() method.
170
- Defining a filter dynamically will take precedent over any other filters defined for the model.
171
-
172
- ```typescript
173
- import type { HttpContext } from '@adonisjs/core/http'
174
- import ProductFilter from '#models/filters/product_filter'
175
- import ProductExclusiveFilter from '#models/filters/product_exclusive_filter'
176
-
177
- export default class ProductsController {
178
- async index({ request, auth }: HttpContext): Promise<Product[]> {
179
- const filter = auth.user.isAdmin() ? ProductFilter : ProductExclusiveFilter
180
- return Product.filter(request.all(), filter).orderBy('created_at', 'desc')
181
- }
182
- }
183
- ```
184
-
185
- ### Filtering relations
186
-
187
- For filtering relations of model may be use `.query().filter()` or scope `filtration` , example:
188
-
189
- ```typescript
190
- import type { HttpContext } from '@adonisjs/core/http'
191
- import ProductCategory from '#models/product_category'
192
-
193
- export default class ProductCategoriesController {
194
- /**
195
- * Get a list products of product category
196
- * GET /product-categories/:product_category_id/products
197
- */
198
- async index({ params, request }: HttpContext): Promise<Product[]> {
199
- const productCategory: ProductCategory = await ProductCategory.findOrFail(
200
- params.product_category_id
201
- )
202
-
203
- return productCategory
204
- .related('products')
205
- .query()
206
- .filter(request.all())
207
- .orderBy('created_at', 'desc')
208
- }
209
- }
210
- ```
211
-
212
- Documentation by [Query Scopes](https://lucid.adonisjs.com/docs/model-query-scopes)
213
-
214
- **Note:** The relation model must be `Filterable` and `$filter` must be defined in it
215
-
216
- ## License
217
-
218
- This project is [MIT](https://github.com/codenameryuu/adonis-lucid-filter/blob/master/LICENSE.md) licensed.
1
+ # @codenameryuu/adonis-lucid-filter
2
+
3
+ This addon adds the functionality to filter Lucid Models Adonis JS 7. Inspired by [EloquentFilter](https://github.com/Tucker-Eric/EloquentFilter)
4
+
5
+ ## Requirement
6
+
7
+ * Adonis Js 7
8
+ * Lucid 22 or higher
9
+
10
+ ## Installation
11
+
12
+ * Install the package
13
+
14
+ ```bash
15
+ yarn add @codenameryuu/adonis-lucid-filter
16
+ ```
17
+
18
+ * Configure the package
19
+
20
+ ```bash
21
+ node ace configure @codenameryuu/adonis-lucid-filter
22
+ ```
23
+
24
+ * Make sure to register the provider inside `adonisrc.ts` file.
25
+
26
+ ```typescript
27
+ providers: [
28
+ // ...
29
+ () => import('@codenameryuu/adonis-lucid-filter/provider'),
30
+ ],
31
+ commands: [
32
+ // ...
33
+ () => import('@codenameryuu/adonis-lucid-filter/commands')
34
+ ]
35
+ ```
36
+
37
+ ## Usage
38
+
39
+ You can create a model filter with the following ace command:
40
+
41
+ ```bash
42
+ node ace make:filter product
43
+ ```
44
+
45
+ Where `product` is the Lucid Model you are creating the filter for. This will create `app/models/filters/product_filter.ts`
46
+
47
+ ### Defining The Filter Logic
48
+
49
+ Define the filter logic based on the camel cased input key passed to the `filter()` method.
50
+
51
+ * Empty strings are ignored
52
+ * `setup()` will be called regardless of input
53
+ * `_id` is dropped from the end of the input to define the method so filtering `product_id` would use the `product()` method
54
+ * Input without a corresponding filter method are ignored
55
+ * The value of the key is injected into the method
56
+ * All values are accessible through the `this.$input` a property
57
+ * All QueryBuilder methods are accessible in `this.$query` object in the model filter class.
58
+
59
+ To define methods for the following input:
60
+
61
+ ```json
62
+ {
63
+ "productCategoryId": 1,
64
+ "name": "Car",
65
+ "price": 100000
66
+ }
67
+ ```
68
+
69
+ You would use the following methods:
70
+
71
+ ```typescript
72
+ import { BaseModelFilter } from '@codenameryuu/adonis-lucid-filter'
73
+ import type { ModelQueryBuilderContract } from '@adonisjs/lucid/types/model'
74
+ import Product from '#models/product'
75
+
76
+ export default class ProductFilter extends BaseModelFilter {
77
+ declare $query: ModelQueryBuilderContract<typeof Product>
78
+
79
+ // Blacklisted methods
80
+ static blacklist: string[] = ['secretMethod']
81
+
82
+ // Dropped `_id` from the end of the input
83
+ // Doing this would allow you to have a `company()` filter method as well as a `companyId()` filter method.
84
+ static dropId: boolean = true
85
+
86
+ // Doing this would allow you to have a mobile_phone() filter method instead of mobilePhone().
87
+ // By default, mobilePhone() filter method can be called thanks to one of the following input key:
88
+ // mobile_phone, mobilePhone, mobile_phone_id, mobilePhoneId
89
+ static camelCase: boolean = true
90
+
91
+ // This will filter 'productCategoryId', 'product_category_id' OR 'productCategory'
92
+ productCategory(id: number) {
93
+ this.$query.where('product_category_id', id)
94
+ }
95
+
96
+ name(name: string) {
97
+ this.$query.where('name', 'LIKE', `%${name}%`)
98
+ }
99
+
100
+ price(price: number) {
101
+ this.$query.where('price', price)
102
+ }
103
+
104
+ secretMethod(secretParameter: any) {
105
+ this.$query.where('some_column', true)
106
+ }
107
+ }
108
+ ```
109
+
110
+ #### Blacklist
111
+
112
+ Any methods defined in the `blacklist` array will not be called by the filter.
113
+ Those methods are normally used for internal filter logic.
114
+
115
+ The `whitelistMethod()` methods can be used to dynamically blacklist methods.
116
+
117
+ Example:
118
+
119
+ ```typescript
120
+ setup($query) {
121
+ this.whitelistMethod('secretMethod')
122
+ this.$query.where('is_admin', true)
123
+ }
124
+ ```
125
+
126
+ > `setup()` not may be async
127
+
128
+ > **Note:** All methods inside `setup()` will be called every time `filter()` is called on the model
129
+
130
+ In the example above `secretMethod()` will not be called, even if there is a `secret_method` key in the input object.
131
+ In order to call this method it would need to be whitelisted dynamically:
132
+
133
+ ### Applying The Filter To A Model
134
+
135
+ ```typescript
136
+ import { compose } from '@adonisjs/core/helpers'
137
+ import { Filterable } from '@codenameryuu/adonis-lucid-filter'
138
+
139
+ import ProductFilter from '#models/filters/product_filter'
140
+
141
+ export default class Product extends compose(BaseModel, Filterable) {
142
+ static $filter = () => ProductFilter
143
+
144
+ // ...columns and props
145
+ }
146
+ ```
147
+
148
+ This gives you access to the `filter()` method that accepts an object of input:
149
+
150
+ ```typescript
151
+ import type { HttpContext } from '@adonisjs/core/http'
152
+ import Product from '#models/product'
153
+
154
+ export default class ProductsController {
155
+ async index({ request }: HttpContext): Promise<Product[]> {
156
+ return Product.filter(request.all()).orderBy('created_at', 'desc')
157
+ }
158
+
159
+ // or with paginate method
160
+
161
+ async index({ request }: HttpContext): Promise<ModelPaginatorContract<Product>> {
162
+ return Product.filter(request.all()).paginate(1, 10)
163
+ }
164
+ }
165
+ ```
166
+
167
+ ### Dynamic Filters
168
+
169
+ You can define the filter dynamically by passing the filter to use as the second parameter of the filter() method.
170
+ Defining a filter dynamically will take precedent over any other filters defined for the model.
171
+
172
+ ```typescript
173
+ import type { HttpContext } from '@adonisjs/core/http'
174
+ import ProductFilter from '#models/filters/product_filter'
175
+ import ProductExclusiveFilter from '#models/filters/product_exclusive_filter'
176
+
177
+ export default class ProductsController {
178
+ async index({ request, auth }: HttpContext): Promise<Product[]> {
179
+ const filter = auth.user.isAdmin() ? ProductFilter : ProductExclusiveFilter
180
+ return Product.filter(request.all(), filter).orderBy('created_at', 'desc')
181
+ }
182
+ }
183
+ ```
184
+
185
+ ### Filtering relations
186
+
187
+ For filtering relations of model may be use `.query().filter()` or scope `filtration` , example:
188
+
189
+ ```typescript
190
+ import type { HttpContext } from '@adonisjs/core/http'
191
+ import ProductCategory from '#models/product_category'
192
+
193
+ export default class ProductCategoriesController {
194
+ /**
195
+ * Get a list products of product category
196
+ * GET /product-categories/:product_category_id/products
197
+ */
198
+ async index({ params, request }: HttpContext): Promise<Product[]> {
199
+ const productCategory: ProductCategory = await ProductCategory.findOrFail(
200
+ params.product_category_id
201
+ )
202
+
203
+ return productCategory
204
+ .related('products')
205
+ .query()
206
+ .filter(request.all())
207
+ .orderBy('created_at', 'desc')
208
+ }
209
+ }
210
+ ```
211
+
212
+ Documentation by [Query Scopes](https://lucid.adonisjs.com/docs/model-query-scopes)
213
+
214
+ **Note:** The relation model must be `Filterable` and `$filter` must be defined in it
215
+
216
+ ## License
217
+
218
+ This project is [MIT](https://github.com/codenameryuu/adonis-lucid-filter/blob/master/LICENSE.md) licensed.
@@ -1 +1 @@
1
- {"commands":[],"version":1}
1
+ {"commands":[{"commandName":"make:filter","description":"Make a new Lucid filter","help":"","namespace":"make","aliases":[],"flags":[],"args":[{"name":"name","argumentName":"name","required":true,"description":"Name of the model file","type":"string"}],"options":{},"filePath":"make_filter.js"}],"version":1}
@@ -1,4 +1,4 @@
1
- import { BaseCommand } from '@adonisjs/core/ace';
1
+ import { BaseCommand } from "@adonisjs/core/ace";
2
2
  export default class MakeFilter extends BaseCommand {
3
3
  static commandName: string;
4
4
  static description: string;
@@ -0,0 +1,24 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ import { BaseCommand, args } from "@adonisjs/core/ace";
8
+ import { stubsRoot } from "../stubs/main.js";
9
+ export default class MakeFilter extends BaseCommand {
10
+ static commandName = "make:filter";
11
+ static description = "Make a new Lucid filter";
12
+ /**
13
+ * Run command
14
+ */
15
+ async run() {
16
+ const codemods = await this.createCodemods();
17
+ await codemods.makeUsingStub(stubsRoot, "make/filter/main.stub", {
18
+ name: this.name,
19
+ });
20
+ }
21
+ }
22
+ __decorate([
23
+ args.string({ description: "Name of the model file" })
24
+ ], MakeFilter.prototype, "name", void 0);
@@ -1,2 +1,2 @@
1
- import type Configure from '@adonisjs/core/commands/configure';
1
+ import type Configure from "@adonisjs/core/commands/configure";
2
2
  export declare function configure(command: Configure): Promise<void>;
@@ -0,0 +1,7 @@
1
+ export async function configure(command) {
2
+ const codemods = await command.createCodemods();
3
+ await codemods.updateRcFile((rcFile) => {
4
+ rcFile.addProvider("@codenameryuu/adonis-lucid-filter/provider");
5
+ rcFile.addCommand("@codenameryuu/adonis-lucid-filter/commands");
6
+ });
7
+ }
package/build/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { configure } from './configure.js';
2
- export { stubsRoot } from './stubs/main.js';
3
- export { BaseModelFilter } from './src/base_model.js';
4
- export { Filterable } from './src/mixin.js';
1
+ export { configure } from "./configure.js";
2
+ export { stubsRoot } from "./stubs/main.js";
3
+ export { BaseModelFilter } from "./src/base_model.js";
4
+ export { Filterable } from "./src/mixin.js";
package/build/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export { configure } from "./configure.js";
2
+ export { stubsRoot } from "./stubs/main.js";
3
+ export { BaseModelFilter } from "./src/base_model.js";
4
+ export { Filterable } from "./src/mixin.js";
@@ -7,7 +7,7 @@
7
7
  exports({ to: app.modelsPath('filters', entity.path, modelFilterFileName) })
8
8
  }}}
9
9
 
10
- import { BaseModelFilter } from 'adonis-lucid-filter'
10
+ import { BaseModelFilter } from '@codenameryuu/adonis-lucid-filter'
11
11
  import type { ModelQueryBuilderContract } from '@adonisjs/lucid/types/model'
12
12
  import {{ modelName }} from '#models/{{ modelFileName }}'
13
13
 
@@ -1,4 +1,4 @@
1
- import type { ApplicationService } from '@adonisjs/core/types';
1
+ import type { ApplicationService } from "@adonisjs/core/types";
2
2
  export default class LucidFilterProvider {
3
3
  protected app: ApplicationService;
4
4
  constructor(app: ApplicationService);
@@ -0,0 +1,12 @@
1
+ /// <reference path="../src/types/querybuilder.ts" />
2
+ import { extendModelQueryBuilder } from "../src/bindings/model_query_builder.js";
3
+ export default class LucidFilterProvider {
4
+ app;
5
+ constructor(app) {
6
+ this.app = app;
7
+ }
8
+ async boot() {
9
+ const { ModelQueryBuilder } = await this.app.import("@adonisjs/lucid/orm");
10
+ extendModelQueryBuilder(ModelQueryBuilder);
11
+ }
12
+ }
@@ -1,4 +1,4 @@
1
- import type { LucidFilter } from './types/filter.js';
1
+ import type { LucidFilter } from "./types/filter.js";
2
2
  /**
3
3
  * Class to filtering AdonisJS Lucid ORM
4
4
  *
@@ -8,7 +8,7 @@ import type { LucidFilter } from './types/filter.js';
8
8
  export declare class BaseModelFilter implements LucidFilter {
9
9
  $query: any;
10
10
  $input: object;
11
- ['constructor']: typeof BaseModelFilter;
11
+ ["constructor"]: typeof BaseModelFilter;
12
12
  $blacklist: string[];
13
13
  static blacklist: string[];
14
14
  static dropId: boolean;
@@ -0,0 +1,82 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var BaseModelFilter_1;
8
+ import camelCase from "lodash/camelCase.js";
9
+ function StaticImplements() {
10
+ return (_t) => { };
11
+ }
12
+ /**
13
+ * Class to filtering AdonisJS Lucid ORM
14
+ *
15
+ * @class BaseModelFilter
16
+ * @constructor
17
+ */
18
+ let BaseModelFilter = class BaseModelFilter {
19
+ static { BaseModelFilter_1 = this; }
20
+ $query;
21
+ $input;
22
+ static blacklist = [];
23
+ static dropId = true;
24
+ static camelCase = true;
25
+ constructor($query, $input) {
26
+ this.$query = $query;
27
+ this.$input = $input;
28
+ this.$input = BaseModelFilter_1.removeEmptyInput(this.$input);
29
+ this.$blacklist = this.constructor.blacklist;
30
+ }
31
+ handle() {
32
+ if (this.setup && typeof this.setup === "function") {
33
+ this.setup(this.$query);
34
+ }
35
+ this.$filterByInput();
36
+ return this.$query;
37
+ }
38
+ whitelistMethod(method) {
39
+ const index = this.$blacklist.indexOf(method);
40
+ const isBlacklisted = index !== -1;
41
+ if (isBlacklisted)
42
+ this.$blacklist.splice(index, 1);
43
+ return isBlacklisted;
44
+ }
45
+ $filterByInput() {
46
+ for (const key in this.$input) {
47
+ const method = this.$getFilterMethod(key);
48
+ const keyName = key;
49
+ const value = this.$input[keyName];
50
+ if (this.$methodIsCallable(method)) {
51
+ this[method](value);
52
+ }
53
+ }
54
+ }
55
+ $getFilterMethod(key) {
56
+ const methodName = this.constructor.dropId ? key.replace(/^(.*)(_id|Id)$/, "$1") : key;
57
+ return this.constructor.camelCase ? camelCase(methodName) : methodName;
58
+ }
59
+ static removeEmptyInput(input) {
60
+ const filteredInput = {};
61
+ for (const key in input) {
62
+ const keyName = key;
63
+ const value = input[keyName];
64
+ if (value !== "" && value !== null && value !== undefined) {
65
+ filteredInput[keyName] = value;
66
+ }
67
+ }
68
+ return filteredInput;
69
+ }
70
+ $methodIsCallable(method) {
71
+ const methodKey = method;
72
+ return !!this[methodKey] && typeof this[methodKey] === "function" && !this.$methodIsBlacklisted(method);
73
+ }
74
+ $methodIsBlacklisted(method) {
75
+ return this.$blacklist.includes(method);
76
+ }
77
+ };
78
+ BaseModelFilter = BaseModelFilter_1 = __decorate([
79
+ StaticImplements()
80
+ ], BaseModelFilter);
81
+ export { BaseModelFilter };
82
+ export default BaseModelFilter;
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Define filter method to ModelQueryBuilder
3
+ */
4
+ export function extendModelQueryBuilder(builder) {
5
+ builder.macro("filter", function (input, filter) {
6
+ const Filter = filter || this.model.$filter();
7
+ return new Filter(this, input).handle();
8
+ });
9
+ }
@@ -1,7 +1,7 @@
1
- import type { NormalizeConstructor } from '@adonisjs/core/types/helpers';
2
- import type { BaseModel } from '@adonisjs/lucid/orm';
3
- import type { InputObject, LucidFilterContract } from '@codenameryuu/adonis-lucid-filter/types/filter';
4
- import type { ModelQueryBuilderContract, QueryScope, QueryScopeCallback } from '@adonisjs/lucid/types/model';
1
+ import type { NormalizeConstructor } from "@adonisjs/core/types/helpers";
2
+ import type { BaseModel } from "@adonisjs/lucid/orm";
3
+ import type { InputObject, LucidFilterContract } from "@codenameryuu/adonis-lucid-filter/types/filter";
4
+ import type { ModelQueryBuilderContract, QueryScope, QueryScopeCallback } from "@adonisjs/lucid/types/model";
5
5
  export declare const Filterable: <Model extends NormalizeConstructor<typeof BaseModel>>(superclass: Model) => {
6
6
  new (...args: any[]): {
7
7
  $attributes: import("@adonisjs/lucid/types/model").ModelObject;
@@ -0,0 +1,19 @@
1
+ export const Filterable = (superclass) => {
2
+ class FilterableModel extends superclass {
3
+ /**
4
+ * Filter method of filterable model
5
+ */
6
+ static filter(input, filter) {
7
+ const Filter = filter || this.$filter();
8
+ return new Filter(this.query(), input).handle();
9
+ }
10
+ /**
11
+ * Filtration scope of filterable model
12
+ */
13
+ static filtration = function (query, input, filter) {
14
+ const Filter = filter || this.$filter();
15
+ return new Filter(query, input).handle();
16
+ };
17
+ }
18
+ return FilterableModel;
19
+ };
@@ -1,5 +1,5 @@
1
- import type { CamelCase, SnakeCase, Split } from 'type-fest';
2
- import type { LucidModel, LucidRow, ModelQueryBuilderContract } from '@adonisjs/lucid/types/model';
1
+ import type { CamelCase, SnakeCase, Split } from "type-fest";
2
+ import type { LucidModel, LucidRow, ModelQueryBuilderContract } from "@adonisjs/lucid/types/model";
3
3
  /**
4
4
  * Lucid filter instance
5
5
  */
@@ -26,13 +26,13 @@ export interface LucidFilterContract {
26
26
  * Pick keys from methods of filter with a type of first value
27
27
  */
28
28
  type PickKeys<Filter> = {
29
- [Key in keyof Filter as SnakeCase<Exclude<Key, keyof LucidFilter | 'constructor'>>]: Filter[Key] extends (value: infer V, ...args: any) => any ? V : never;
29
+ [Key in keyof Filter as SnakeCase<Exclude<Key, keyof LucidFilter | "constructor">>]: Filter[Key] extends (value: infer V, ...args: any) => any ? V : never;
30
30
  };
31
31
  /**
32
32
  * Add `_id` to end of SnakeCase keys with number type
33
33
  */
34
34
  type KeysWithIds<SCKeys> = {
35
- [Key in keyof SCKeys as Key extends string ? 'id' extends Split<Key, '_'>[number] ? never : SCKeys[Key] extends number ? `${string & Key}_id` : never : never]?: SCKeys[Key];
35
+ [Key in keyof SCKeys as Key extends string ? "id" extends Split<Key, "_">[number] ? never : SCKeys[Key] extends number ? `${string & Key}_id` : never : never]?: SCKeys[Key];
36
36
  };
37
37
  /**
38
38
  * Convert all keys to CamelCase
@@ -0,0 +1 @@
1
+ export {};
@@ -1,5 +1,5 @@
1
- import type { LucidFilterContract, InputObject } from '@codenameryuu/adonis-lucid-filter/types/filter';
2
- declare module '@adonisjs/lucid/types/model' {
1
+ import type { LucidFilterContract, InputObject } from "@codenameryuu/adonis-lucid-filter/types/filter";
2
+ declare module "@adonisjs/lucid/types/model" {
3
3
  type FilterableModel = LucidModel & {
4
4
  $filter: () => LucidFilterContract;
5
5
  filtration: QueryScope<LucidModel, QueryScopeCallback>;
@@ -8,7 +8,7 @@ declare module '@adonisjs/lucid/types/model' {
8
8
  [Method in keyof Methods]: Model extends FilterableModel ? Methods[Method] : never;
9
9
  };
10
10
  type FilterableMethods<Model extends LucidModel> = {
11
- filter<Filter extends LucidFilterContract = ReturnType<(FilterableModel & Model)['$filter']>>(input: InputObject<InstanceType<Filter>>, filter?: Filter): ModelQueryBuilderContract<Model, InstanceType<Model>>;
11
+ filter<Filter extends LucidFilterContract = ReturnType<(FilterableModel & Model)["$filter"]>>(input: InputObject<InstanceType<Filter>>, filter?: Filter): ModelQueryBuilderContract<Model, InstanceType<Model>>;
12
12
  };
13
13
  interface ModelQueryBuilderContract<Model extends LucidModel, Result = InstanceType<Model>> extends ExcludeFilterableMethods<FilterableMethods<Model>, Model> {
14
14
  }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,3 @@
1
+ import { fileURLToPath } from "node:url";
2
+ import { dirname } from "node:path";
3
+ export const stubsRoot = dirname(fileURLToPath(import.meta.url));
package/package.json CHANGED
@@ -1,114 +1,110 @@
1
- {
2
- "name": "@codenameryuu/adonis-lucid-filter",
3
- "description": "Addon for filtering Adonis JS 7 Lucid ORM",
4
- "version": "3.1.0",
5
- "author": "codenameryuu",
6
- "license": "MIT",
7
- "homepage": "https://github.com/codenameryuu/adonis-lucid-filter#readme",
8
- "repository": {
9
- "type": "git",
10
- "url": "git+https://github.com/codenameryuu/adonis-lucid-filter.git"
11
- },
12
- "engines": {
13
- "node": ">=24.0.0"
14
- },
15
- "type": "module",
16
- "files": [
17
- "build",
18
- "!build/bin",
19
- "!build/tests"
20
- ],
21
- "exports": {
22
- ".": "./build/index.js",
23
- "./commands": "./build/commands/main.js",
24
- "./types/*": "./build/src/types/*.js",
25
- "./bindings": "./build/src/bindings/model_query_builder.js",
26
- "./provider": "./build/providers/lucid_filter_provider.js"
27
- },
28
- "scripts": {
29
- "lint": "eslint .",
30
- "format": "prettier --write .",
31
- "clean": "del-cli build",
32
- "precompile": "npm run lint && npm run clean",
33
- "postcompile": "npm run copy:stubs && npm run index:commands",
34
- "compile": "tsc --emitDeclarationOnly --declaration",
35
- "build": "npm run compile",
36
- "copy:stubs": "copyfiles \"stubs/**/**/*.stub\" --up=\"1\" build",
37
- "index:commands": "adonis-kit index build/commands",
38
- "quick:test": "NODE_DEBUG=\"adonis-lucid-filter\" node --enable-source-maps --loader=ts-node/esm bin/test.ts",
39
- "pretest": "npm run lint",
40
- "test": "c8 npm run quick:test",
41
- "typecheck": "tsc --noEmit",
42
- "version": "npm run build",
43
- "prepublishOnly": "npm run build",
44
- "release": "np"
45
- },
46
- "devDependencies": {
47
- "@adonisjs/assembler": "^7.7.0",
48
- "@adonisjs/core": "^7.0.0",
49
- "@adonisjs/eslint-config": "^3.0.0",
50
- "@adonisjs/lucid": "^22.0.0",
51
- "@adonisjs/prettier-config": "^1.4.5",
52
- "@adonisjs/tsconfig": "^2.0.0",
53
- "@japa/assert": "^4.2.0",
54
- "@japa/expect-type": "^2.0.4",
55
- "@japa/file-system": "^3.0.0",
56
- "@japa/runner": "^5.3.0",
57
- "@japa/snapshot": "^2.0.5",
58
- "@swc/core": "^1.6.7",
59
- "@types/lodash": "^4.17.6",
60
- "@types/node": "^25.5.0",
61
- "c8": "^9.1.0",
62
- "copyfiles": "^2.4.1",
63
- "del-cli": "^5.1.0",
64
- "eslint": "^10.0.2",
65
- "knex": "^3.1.0",
66
- "lodash": "^4.17.23",
67
- "luxon": "^3.4.4",
68
- "np": "^11.0.2",
69
- "prettier": "^3.8.1",
70
- "reflect-metadata": "^0.2.2",
71
- "ts-node": "^10.9.2",
72
- "tsup": "^8.1.0",
73
- "typescript": "^5.5.3",
74
- "youch": "^4.1.0"
75
- },
76
- "dependencies": {
77
- "type-fest": "^4.21.0"
78
- },
79
- "peerDependencies": {
80
- "@adonisjs/core": "^7.0.0",
81
- "@adonisjs/lucid": "^22.0.0"
82
- },
83
- "keywords": [
84
- "adonisjs",
85
- "adonisjs-filter",
86
- "adonisjs-lucid",
87
- "adonisjs-lucid-filter",
88
- "adonis",
89
- "adonis-lucid",
90
- "adonis-filter",
91
- "adonis-lucid-filter"
92
- ],
93
- "prettier": "@adonisjs/prettier-config",
94
- "publishConfig": {
95
- "access": "public",
96
- "tag": "latest"
97
- },
98
- "np": {
99
- "message": "chore(release): %s",
100
- "tag": "latest",
101
- "branch": "master",
102
- "anyBranch": false
103
- },
104
- "c8": {
105
- "reporter": [
106
- "text",
107
- "html"
108
- ],
109
- "exclude": [
110
- "tests/**",
111
- "bin/**"
112
- ]
113
- }
114
- }
1
+ {
2
+ "name": "@codenameryuu/adonis-lucid-filter",
3
+ "description": "Addon for filtering Adonis JS with Lucid ORM",
4
+ "version": "3.2.1",
5
+ "author": "codenameryuu",
6
+ "license": "MIT",
7
+ "homepage": "https://github.com/codenameryuu/adonis-lucid-filter#readme",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/codenameryuu/adonis-lucid-filter.git"
11
+ },
12
+ "engines": {
13
+ "node": ">=24.0.0"
14
+ },
15
+ "type": "module",
16
+ "files": [
17
+ "build",
18
+ "!build/bin",
19
+ "!build/tests"
20
+ ],
21
+ "exports": {
22
+ ".": "./build/index.js",
23
+ "./commands": "./build/commands/main.js",
24
+ "./types/*": "./build/src/types/*.js",
25
+ "./bindings": "./build/src/bindings/model_query_builder.js",
26
+ "./provider": "./build/providers/lucid_filter_provider.js"
27
+ },
28
+ "scripts": {
29
+ "format": "prettier --write .",
30
+ "clean": "del-cli build",
31
+ "precompile": "npm run clean",
32
+ "postcompile": "npm run copy:stubs && npm run index:commands",
33
+ "compile": "tsc",
34
+ "build": "npm run compile",
35
+ "copy:stubs": "copyfiles \"stubs/**/**/*.stub\" --up=\"1\" build",
36
+ "index:commands": "adonis-kit index build/commands",
37
+ "quick:test": "NODE_DEBUG=\"adonis-lucid-filter\" node --enable-source-maps --loader=ts-node/esm bin/test.ts",
38
+ "test": "c8 npm run quick:test",
39
+ "typecheck": "tsc --noEmit",
40
+ "version": "npm run build",
41
+ "prepublishOnly": "npm run build",
42
+ "release": "np"
43
+ },
44
+ "devDependencies": {
45
+ "@adonisjs/assembler": "^7.7.0",
46
+ "@adonisjs/core": "^7.0.0",
47
+ "@adonisjs/lucid": "^22.0.0",
48
+ "@adonisjs/prettier-config": "^1.4.5",
49
+ "@adonisjs/tsconfig": "^2.0.0",
50
+ "@japa/assert": "^4.2.0",
51
+ "@japa/expect-type": "^2.0.4",
52
+ "@japa/file-system": "^3.0.0",
53
+ "@japa/runner": "^5.3.0",
54
+ "@japa/snapshot": "^2.0.5",
55
+ "@swc/core": "^1.6.7",
56
+ "@types/lodash": "^4.17.6",
57
+ "@types/node": "^25.5.0",
58
+ "c8": "^9.1.0",
59
+ "copyfiles": "^2.4.1",
60
+ "del-cli": "^5.1.0",
61
+ "knex": "^3.1.0",
62
+ "lodash": "^4.17.23",
63
+ "luxon": "^3.4.4",
64
+ "np": "^11.0.2",
65
+ "prettier": "^3.8.1",
66
+ "reflect-metadata": "^0.2.2",
67
+ "ts-node": "^10.9.2",
68
+ "tsup": "^8.1.0",
69
+ "typescript": "^5.5.3",
70
+ "youch": "^4.1.0"
71
+ },
72
+ "dependencies": {
73
+ "type-fest": "^4.21.0"
74
+ },
75
+ "peerDependencies": {
76
+ "@adonisjs/core": "^7.0.0",
77
+ "@adonisjs/lucid": "^22.0.0"
78
+ },
79
+ "keywords": [
80
+ "adonisjs",
81
+ "adonisjs-filter",
82
+ "adonisjs-lucid",
83
+ "adonisjs-lucid-filter",
84
+ "adonis",
85
+ "adonis-lucid",
86
+ "adonis-filter",
87
+ "adonis-lucid-filter"
88
+ ],
89
+ "prettier": "@adonisjs/prettier-config",
90
+ "publishConfig": {
91
+ "access": "public",
92
+ "tag": "latest"
93
+ },
94
+ "np": {
95
+ "message": "chore(release): %s",
96
+ "tag": "latest",
97
+ "branch": "master",
98
+ "anyBranch": false
99
+ },
100
+ "c8": {
101
+ "reporter": [
102
+ "text",
103
+ "html"
104
+ ],
105
+ "exclude": [
106
+ "tests/**",
107
+ "bin/**"
108
+ ]
109
+ }
110
+ }