How to add external model to ObjectionJS?

183 Views Asked by At

We are using ObjectionJS in our app (Express + NodeJs + Mysql) for a log time but now I want to refactor the code in order to make easier to read and faster to implement, so one of my first approach is to make Objection Model import an external model. This way I don't have to repeat all model fields twice in my business model and again in the objection model. I have search a lot but nothing tells how must be done. Do you have any idea? Thank you very much.

Here is one my models.

export class ExtraSkills extends BaseModel {

    extraSkillID?: number;
    extraSkillAll?: number;
    extraSkillChilds?: number;

    static get tableName() {
        return "OFFERS_EXTRA_SKILLS";
    }

    static get idColumn() {
        return "OFFERS_EXTRA_SKILLS";
    }
}

It would be great if Objection model have some method to import another model in order to avoid redefining same fields...

2

There are 2 best solutions below

1
On

Looks like what you are trying to do is to create objection plugins:

https://vincit.github.io/objection.js/guide/plugins.html

In addition to just creating plugins with implementation and fields you might need to create also some interfaces for typescript to understand that certain class also provides those plugin fields / methods.

0
On

you need to define a base model that extends the Model class from objection, then you can can extend BaseModel in any real model class you're using.