Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 11 additions & 3 deletions src/filters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,10 +120,18 @@ export const filter = {
* Full control: receive the Lucid query builder and the raw value.
* Scopes, joins and subqueries all work here.
*/
custom(
handler: (query: FilterQuery, value: unknown, context: FilterContext) => void
custom<Model extends LucidModel = LucidModel>(
handler: (
query: ModelQueryBuilderContract<Model>,
value: unknown,
context: FilterContext
) => void
): FilterHandler {
return handler
// One cast here instead of one in every handler that names a
// relation: statics cannot reference class type parameters, so the
// stored FilterHandler stays wide while the declaration site gets
// the concrete model.
return handler as FilterHandler
},
}

Expand Down
20 changes: 20 additions & 0 deletions tests/unit/filters.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -161,3 +161,23 @@ test.group('filter handlers receive the request context', () => {
assert.isUndefined(captured.ctx)
})
})

test.group('filter.custom is generic over the model', () => {
test('a typed handler uses relation names without casting', ({ assert }) => {
// The point is the typecheck: whereHas('comments') only compiles
// because custom<typeof Article> narrows the query builder. An
// untyped handler sees ModelQueryBuilderContract<LucidModel>, where
// relation names do not exist.
const handler = filter.custom<typeof Article>((query) => {
// compile-time proof: the narrowed builder knows Article's
// relation names, so 'comments' is assignable where the wide
// builder would reject it as never
type RelationName = Parameters<typeof query.whereHas>[0]
const relation: RelationName = 'comments'
void relation
})

// runtime: custom passes the handler through untouched
assert.isFunction(handler)
})
})