forked from lookinlab/adonis-lucid-filter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmixin.ts
54 lines (50 loc) · 1.5 KB
/
mixin.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/*
* adonis-lucid-filter
*
* (c) Lookin Anton <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
import type { NormalizeConstructor } from '@adonisjs/core/types/helpers'
import type { BaseModel } from '@adonisjs/lucid/orm'
import type { InputObject, LucidFilterContract } from 'adonis-lucid-filter/types/filter'
import type {
ModelQueryBuilderContract,
QueryScope,
QueryScopeCallback,
} from '@adonisjs/lucid/types/model'
export const Filterable = <Model extends NormalizeConstructor<typeof BaseModel>>(
superclass: Model
) => {
class FilterableModel extends superclass {
declare static $filter: () => LucidFilterContract
/**
* Filter method of filterable model
*/
static filter<
T extends typeof FilterableModel,
Filter extends LucidFilterContract = ReturnType<T['$filter']>,
>(
this: T,
input: InputObject<InstanceType<Filter>>,
filter?: Filter
): ModelQueryBuilderContract<T> {
const Filter = filter || this.$filter()
return new Filter(this.query(), input).handle()
}
/**
* Filtration scope of filterable model
*/
static filtration = function (
this: typeof FilterableModel,
query,
input,
filter?: LucidFilterContract
) {
const Filter = filter || this.$filter()
return new Filter(query, input).handle()
} as QueryScope<Model, QueryScopeCallback>
}
return FilterableModel
}