-
Notifications
You must be signed in to change notification settings - Fork 51
API: Database Operations with Objection.js
The Objection.js documentation is very extensive; if you think there should be an elegant way to do something there probably is.
There are models and schemas defined with many useful functions available.
The models should define any relations that are present so that they can be loaded using.
For example, a lesson has chapters so you can define the relationship on the Lesson model:
// models/lesson.js
chapters: {
relation: Model.HasManyRelation,
modelClass: __dirname + '/chapter',
join: {
from: 'lessons.id',
to: 'chapters.lesson_id'
}
}
And it can later be used to include the relations in the API response:
// routes/lessons.js
const lessons = await Lesson.query().where('id', id).eager('chapters');
In order to keep things concise and avoid repetition, it's best to use a modifier to only fetch the relations ID. Ember will fetch the records separately if it needs, this is defined on the child relation's model.
// models/chapter.js
static get modifiers() {
return {
onlyId(builder) {
builder.select('id');
}
};
}
// routes/lessons.js
const lessons = await Lesson.query().where('id', id).eager('chapters(onlyId)');
now instead of:
[
{
id: 1,
title: 'Lesson 1',
description: 'The First Lesson',
chapters: [
{
id: 1,
title: 'Chapter 1',
description: 'The First Chapter',
},
{
id: 2,
title: 'Chapter 2',
description: 'The First Chapter',
}
]
}
]
we'll get:
[
{
id: 1,
title: 'Lesson 1',
description: 'The First Lesson',
chapters: [
{
id: 1
},
{
id: 2
}
]
}
];
There is a _model.js class that all models should extend with some additional functionality like parsing the model to JSON and back in an ember friendly way, and for hiding fields which should not be exposed.
The schemas are used for validation of JSON and models, they will be more or less the same but may have differences. The schemas are included in the Objection.js models for validating input. And they can be used for testing the response of the API using mocha.
Use them to validate whether fields should exist or not and to check the types, as well as more powerful validations like length, email, regex etc.