objection.js icon indicating copy to clipboard operation
objection.js copied to clipboard

Extending my Model class from a Typescript interface breaks relatedQuery

Open vsamma opened this issue 5 years ago • 9 comments

Hi all,

I have been trying to work with Knex and Objection for almost a year now and I have still some problems and confusions about it.

So one of the first problems I had was that I wanted to extend my Model classes from my Typescript interfaces, which I used in my business logical layer (I used the repository pattern kind of approach and only wanted to use Models in the repository classes but typescript interfaces in service classes) without having to declare all the properties twice all the time but also having the benefit of returning my Interface typed objects straight from the Repository layer without having to manually map the objects from one type to another.

This problem is also explained here with one potential solution: https://dev.to/tylerlwsmith/using-a-typescript-interface-to-define-model-properties-in-objection-js-1231

So they used declaration merging by having an interface and a class for the model with identical names, interface extending their main interface and class extending the model class, like this:

// project.ts
interface Project {
  id: number;
  name: string;
  createdDate: Date;
  datasets: Dataset[]; //This here is an example of HasManyRelation dependency on Datasets table
}
// project-model.ts
import { Model } from "objection";
import { Project } from "./project";

interface ProjectModel extends Project {}

class ProjectModel extends Model {
  static get tableName() {
    return "projects";
  }
}

export default ProjectModel;

But I don't want to follow that example because I want to avoid default exports. So instead, I had a solution like this:

// project-model.ts
import { Model } from "objection";
import { Project } from "./project";

export class ProjectModel extends Model {
  static get tableName() {
    return "projects";
  }
}

export interface ProjectModel extends Project, Model {}

Either way, it seems both solutions fix my initial problem and allow me to assign QueryBuilder responses straight to my Project interface typed objects and I don't have to type all the properties twice (in my Models and Interfaces).

BUT, now this creates a problem where I can't use relatedQuery, or more specifically RelatedQueryBuilder.

When I try to run this example:

const datasets = await ProjectModel.relatedQuery('datasets').for(1);

Then the "for" function has a red line under it and the error says:

Property 'for' does not exist on type 'never'.ts(2339)

When I remove the interface related code from my ProjectModel class, then the relatedQuery starts working properly.

How can I use them both? Because I don't want to query all the datasets for example just to get their counts etc. And I don't want to implement all of my logic by writing manual queries, that would lose the benefits of having an ORM at all.

Am I doing something incorrectly? I don't think these solutions should be mutually exclusive but maybe I'm missing something obvious and approaching them in the wrong way.

Thanks!

vsamma avatar Jan 04 '21 18:01 vsamma

You can't use both. You need to define the properties for the model class or any of its parent classes. Otherwise the objection typings cannot access the properties. Theres no way to fix this on objection side.

koskimas avatar Jan 04 '21 18:01 koskimas

Hi @koskimas, thanks for the quick reply.

So while what you're saying makes sense, I still wonder what's the best practice then? How is everybody else using this?

I want to keep my Data Access Layer separate from all the other business logic. So I have the model classes and then repository classes which use those model classes to make queries, but their functions should already return my own interfaces so that I wouldn't need to depend on Model classes (and ORM implementational details) in my service layer.

But I still want to force the contract between the objects coming from the Model/DB and objects used in my business logic.

What's the best way to achieve this then?

Should I define the properties twice? In my own interfaces + also Model classes? And then map from Model class object to my custom interface object inside those repository functions where I query the DB (as I don't want to expose Models to other layers)?

Thanks

vsamma avatar Jan 05 '21 14:01 vsamma

I think you are only left with this option

interface Thing {
  id: number;
  name: string;
}

class ThingModel extends Model implements Thing {
  id!: number;
  name!: string;
}

where you do need to declare everything twice, but at least there is no way to forget to declare the properties for the model class because forgetting to do it is an error.

koskimas avatar Jan 05 '21 14:01 koskimas

Okay, then it appears I misunderstood the official docs.

The Models doc page states the following:

Note that in addition to idColumn, you don't define properties, indexes or anything else related to database schema in the model. In objection, database schema is considered a separate concern and should be handled using migrations (opens new window). The reasoning is that every non-trivial project will need migrations anyway. Managing the schema in two places (model and migrations) only makes things more complex in the long run.

I understood that as you shouldn't define class properties (aka db column names) in the Model class and only create the tables and columns in migrations and then Objection reads those names and creates the objects with those properties automagically and that was quite confusing for me because I wasn't able to use autocomplete for the object properties etc. It didn't help that the example model on that page didn't have class properties defined (except in the jsonSchema function).

I remember I tried the approach what you suggested, by implementing my own interface, but had some problems with it.. I think one case would be when I want to use a Partial object as an input for insert for example (when a full interface has creationDate for example but an input object shouldn't have that property).

In that Tyler Smith's dev.to article I referenced in my question, there was a suggestion of creating a type out of the Model class, like this:

class ThingModel extends Model {
  id!: number;
  name!: string;
}

type Thing = ModelObject<ThingModel>;

It seemed to also work with the Partial objects but of course I understand that it's a less decoupled approach than having a fully defined separate interface (which would not need any changes if I were to swap out my ORM layer).

vsamma avatar Jan 05 '21 15:01 vsamma

Hi @koskimas,

Sorry for bothering you again, but I can't seem to find a working solution. I tried your suggestion but wound up with a new problem:

interface Project {
  id: number;
  name: string;
  datasets: Dataset[];
}

class ProjectModel extends Model implements Project {
  id!: number;
  name!: string;
  datasets!: Dataset[];
}

//both also have relationMappings between each other

interface Dataset {
  id: number;
  name: string;
}

class DatasetModel extends Model implements Dataset {
  id!: number;
  name!: string;
}

So basically, with your suggestion, when I have 2 model classes, one (Project) has the other (Dataset) as an array of children, then the first problem I had was when I set the datasets property type in ProjectModel to Dataset[]. This again broke the relatedQuery. If I swapped it out to DatasetModel[], then it seemed to work.

But now I have a problem with this:

  public async update(id: number, project: Project): Promise<Project> {
    const updatedProject = await ProjectModel.query().patchAndFetchById(id, project);

    return updatedProject;
  }

Patch expects a (partial) ProjectModel but like I said before, I want my Service layer to be decoupled from the Data Access Layer, so the repository functions (like update above) should use my interfaces as input and output types.

And then I get an error, that the datasets property type does not match.

Argument of type 'Project' is not assignable to parameter of type 'PartialModelObject<ProjectModel>'.
  Types of property 'datasets' are incompatible.
    Type 'Dataset[]' is not assignable to type 'DatasetModel[]'.
      Type 'Dataset' is missing the following properties from type 'DatasetModel': $beforeInsert, $beforeUpdate, $relatedQuery, $query, and 30 more.ts(2345)

vsamma avatar Jan 06 '21 17:01 vsamma

I am having the same issue. Somehow typescript infers that the type of relatedQuery is "never". This only happens when I add the type of the "related model" either in the interface definition or even it is itemized in the class definition directly. When I delete the type from the interface, typescript correctly interprets the type of relatedQuery as "QueryBuilder". Which is what we want.
Having the return be a "never" type appears to break the chaining because it does not know how to chain the "never" type. From what I understand of typescript it will infer a "never" type when either a) the function never returns (say an exit() or a infinite loop) or b) if it throws an exception. In this case I walked the relatedQuery code and it does throw an exception .
It seems at a very superficial glance that this is a "typescript" bug or issue, because chaining with exceptions works in javascript and so should work in typescript as well. What I can't understand is why having the type in the interface causes the return type to change from "QueryBuilder" to "never". That would require a knowledge of typescript type inference that I currently don't have. I am considering filing an issue with typescript on this to see if I get any response. @vsamma - how did you work around this (if at all), because I am following a similar code structure in how I have arranged the Model types.

nishant-dani avatar Jun 16 '21 19:06 nishant-dani

Hi @nishant-dani, sorry for the late reply. I forgot about this thread and only remembered it someone called "Marko" replied here last week but it seems his comment has been removed.

So I ended up using the same solution as discussed above.

Firstly, I define an interface. Then I define the Model, which extends Objection's Model and then implements my interface. Now the difference would be that if my Project's interface references Dataset interface for "datasets" property, then for the ProjectModel, the "datasets" property is of type "DatasetModel[]" not "Dataset[]".

So that caused the error that I wrote in my last comment. But the solution to that was easy, I just had to cast the input parameter "project" (that was of type "Project") to "ProjectModel", like this:

public async update(id: number, project: Partial<Project>): Promise<Project> {
    const updatedProject = await ProjectModel.query().patchAndFetchById(
      id,
      project as ProjectModel
    );

    return updatedProject;
  }

And after that simple fix, I haven't had any more problems when working on my project :) Everything works fine now.

vsamma avatar Oct 13 '21 13:10 vsamma

@vsamma Yes, I thought I found a good solution but it fails in some cases. So I deleted the comment to be shure no one else run into problems.

But I found something: PartialModelGraph.

see https://github.com/Vincit/objection.js/issues/2117#issuecomment-935515779

marko-x avatar Oct 13 '21 15:10 marko-x


import { BlogTag } from './BlogTag'; // imported that model
import { IBlogPost } from '../somehere/typef/folder';
import { Model } from "objection";

export class BlogPost extends Model {
  static get tableName() {
    return 'blog_posts';
  }

  static get relationMappings() {
    return {
      tags: {
        relation: Model.HasOneRelation,
        modelClass: BlogTag,   // model reference
        from: 'blog_posts.id',
        tto: 'blog_post_tags.blogPostId',
      },
    };
  }
}


/* Class Interface Merge */
export interface BlogPost extends IBlogPost, Model {
  tag?: BlogTag; // added this here to get $query and other intellisense onthis property
}


/**
* Usage
*/

const result = BlogPost.query().withGraphFetched('tags');
result.tag.$query.patch({})  // i get $query intellisense

// Also this is working correctly
async function update(id: number, blog: Partial<BlogPost>): Promise<BlogPost> {
  const updatedProject = await BlogPost.query().patchAndFetchById(id, blog);
  const datasets = await BlogPost.relatedQuery('tag').for(1);
  return updatedProject;
}


Screenshot from 2022-06-17 15-08-33

kaushal-aubie avatar Jun 17 '22 09:06 kaushal-aubie