objection.js: Typings don't allow custom query builders
I’m trying to create Model, which has extended query builder with .session()
method. However when I’m extending the model and setting our custom query builder there return type of $query()
and other functions still is QueryBuilder<this>
instead of CustomQueryBuilder<this>
.
Simplified (not runnable example):
class CustomQueryBuilder<T> extends QueryBuilder<T> {
session(session: any) {
this.context().session = session;
return this;
}
}
class BaseModel extends Model {
// Override the objection.js query builders classes for subclasses.
static QueryBuilder = CustomQueryBuilder;
static RelatedQueryBuilder = CustomQueryBuilder;
// ... more stuff ...
}
const daa = await BaseModel
.query(trx)
// ERROR: [ts] Property 'session' does not exist on type 'QueryBuilder<BaseModel>'
.session(req.session)
.insert({1:1});
Any ideas how to override this? I wouldn’t like to do casting everywhere I’m using my extended query builder, nor I would like to add extra methods to BaseModel
which would apply correct typing for returned query builder.
About this issue
- Original URL
- State: closed
- Created 7 years ago
- Reactions: 1
- Comments: 71 (32 by maintainers)
Here you go:
We can finally close this one. Fixed in v2.0 branch. Soon to be released
@pulse14 @alidcastano and everyone else who are pissed: The support for typing the custom query builders is not missing because we are lazy or stypid. It’s missing because adding typings for them is borderline impossible. Feel free to try. People have worked hard on trying to solve this problem FOR YOU, FOR FREE, ON THEIR SPARE TIME! Remember this is open source and you have paid nothing for this. If you want to do something, stop complaining and make a PR!
Good news is that it all seems to work. The bad news is that the types need to be completely rewritten.
So for anyone (most people) that didn’t read my comment diarrhea, this is how you would create a custom query builder after the types have been rewritten:
The custom query builder type is correctly inherited over any method call, callback, subquery, etc. With the new types you even get autocomplete for properties when you start to type stuff like
.where('
. I think the new types will be much cleaner too since we don’t need to drag around three template arguments. Instead, we only drag around one, the query builder type.@falkenhawk What’s with the eyes? 😄
God Bless you, JTL. I think it would be fun to hang out with you. 🍻I didn’t read any of this but it’s great
I just can’t agree with that perspective, for a number of reasons. I have three main points that I’ll list to keep it succinct:
As a result of those three, that’s why I’m putting effort into helping with Objections types primarily - I want to get them to a state where people can be confident about their correctness/robustness, as much as is possible with what typescript offers. My goal is to have all of the happy path covered correctly; anything not in the happy path I’m trying to get as much as is possible handled by types as well. Things like what functions can be called, at what time, on the query builder are not something that can be accounted for at this time, for example.
I finally dipped my toes in typescript world. I was able to create this POC of custom query builders. Wouldn’t it be possible to use something like this to be able to type custom query builders? Tell me what I’m missing here @elhigu @mordof @mceachen @jtlapp? This does compile:
This requires you to override the
static query
method for all model classes though. and I believe we need toany
cast forsuper.query()
. Is that too ugly?@tobalsgithub I still cannot get this stuff working, but made some progress and static method overriding seem to work already. $query is still failing, because class is extended from incompatible promise stuff or something like that. I made test project and when its working I’ll add it to greenkeeper (or merge to objection codebase) to keep example working when typings are updated (https://github.com/elhigu/objection-overriding-querybuilder-typescript).
Current error is:
I’ve got some experiments planned should either lead me to the right solution or else send me back here a bit smarter to help.
@jtlapp ooh ok. That part has viable types now 🙂 it’s in the
new-typings
branch, and is being worked on get those covering everything (at minimum) that was previously typed as well.Once that process is done, I’m going to be reviewing absolutely all of the types and ensuring they’re as complete/compatible as they can be. If there’s viable changes to certain areas (e.g. some helpers to define properties on a model) for the actual js that can help improve/solidify the types, without taking away from the core style of objection, i’ll be recommending/making PRs for those as well.
@willsoto The tests need to pass before it can be merged into 2.0
I think I just woke up with a solution 😄 At least for the changing return types, but I think this could be the key for the whole problem.
So the key is to add those three subtypes
MQB
,SQB
andNQB
for the custom query builder and theQB
type for each model, and that’s it! SeeAnimal
andCustomQueryBuilder
in the example above.@koskimas Would you consider into 2.0? It very much sounds like the problem won’t be solved without involving an API break (or at least without restructuring how the types of related things work).
Alternatively, could you propose a recommended way to inject custom methods (like custom where<whatever>) into query builders - our current codebase now has a tens of “as any” typecasts scattered around the codebase and our initial attempt to cleanup code with custom query methods is losing its original purpose.
Would love to help on this one (within the limits that own startup + small kids permits), but probably clear guidelines on how to solve this would help me forward.
When I first looked at Objection, I assumed that I needed a custom query builder. I put a lot of time into trying to find a way to make it work with Typescript, but I’m glad that effort ultimately failed, because it turns out that I didn’t need a custom query builder. The
.context()
method provided everything I needed. (Unfortunately, I’ve been off on a whole 'nother project for a while, but I mean to get back.)@newhouse ask him about spiders
I opted to create a working Typescript version of @koskimas’s custom QueryBuilder found in
examples/plugin
. The README should get you started.It was quite a bear to carry forward the generality of the plugin, but I finally succeeded.
@elhigu I was able to get the static query function definition to work. Try changing the example given by @koskimas to
Haven’t played with it too much, but the typescript does compile at least.
Haven’t figured out the
$query
or$relatedQuery
functions yet, as those seem to require a different type ofQueryBuilderSingle<this>
Sure.
So, I’m pretty sure in order to expose an extension of a QueryBuilder in your model class, we’ll need to extend Model with a generic type, something like:
The problem is that the QueryBuilder signature already has a generic typing associated to it, that points back to the defining Model, and I can’t use a
this
keyword in the generic definition, like this:because
I’m trying to think of a clever workaround here, but if anyone comes up with a solution, I’m receptive.