Vincit / objection.js

An SQL-friendly ORM for Node.js
https://vincit.github.io/objection.js
MIT License
7.28k stars 639 forks source link

relationMappings() function only checks validity of related tables and doesn't check validity of owner table #2280

Open TissuePowder opened 2 years ago

TissuePowder commented 2 years ago

I have two objectionjs models, Meal and MealType that correspond to meal and meal_type tables respectively in the database. I defined a relationship as follows, where Meal is the owner model and MealType is the related model.

class Meal extends BaseModel {
    static get relationMappings() {
        return {
            mealType: {
                relation: BaseModel.BelongsToOneRelation,
                modelClass: require('./mealtype'),
                join: {
                    from: 'meal.mealTypeId',
                    to: 'mealType.id'
                }
            }
        };
    }
}

Now in the join object, if I misspell the name of the related table, or change a case, the error is caught while querying the model. For example, if I do to: 'mealtype.id', (notice the small t instead of T) I get the following error:

"Meal.relationMappings.mealType: join: either `from` or `to` must point to the owner model table and the other one to the related table. It might be that specified table 'mealtype' is not correct"

That's great, but if I misspell anything in the owner table, like if I write from: 'meal.MealTypeId', (notice the M instead of m) I don't get any kind of error. Just, during the Meal.query().withGraphFetched('mealType') query, the returned data of mealType is null.

I personally did a spelling mistake on the owner table's field-name and it took some time to understand where the problem was. So if possible, can we have some kind of validity checking on the owner table as well?

I am using objectionjs 3.0.1 and postgres 14.3. I am also using ...knexSnakeCaseMappers() in knexfile.js.

davidpaulhunt commented 2 years ago

@TissuePowder it looks like only the table names are validated. Likely, that's all objection knows about (via tableName).

Have you verified that related columns are validated? I suspect they aren't and would require some kind of table introspection outside of Objection itself.