Let's assume i have two Models in Objection Books
and Chapters
. What i want to achieve is before inserting Book
to DB to save 1 default entry on Chapters
table and return the creates chapter.id and save it to Books.
What is the best approach ?
What i do now is Using the $beforeInsert hooks and save first the Chapter record and then create the book (i describe it below on the code ).
But this i think may raise issues in the case of the last query fails and in general is a bad practise adding bussiness logic in the Data Model. i was thinking creating BookServices which will include functions like CreateNewBook
where i will have trasanctions doing all the inserts and logic to the Db. So then i can use those BookServices in whatever controller need that logic.
What do you think is the best approach on that ? Should i couple this logic to the model Layer or move it on Services Layer ?
What i do right now is :
Controller -- createBook.js
const book = require('Book')
createBook : () => {
const newBook = new Book({title: "My Title", chapters: [], author: "My Author"})
newBook.save()
}
Model -- Book.js
const Chapter = require('Chapter')
const { Model } = require('objection');
class Book extends Model {
static get tableName() {
return 'books';
}
$beforeInsert() {
super.$beforeInsert()
const newChapter = new Chapter({title: 'FrontMatter'})
const savedChapter = newChapter.save()
this.chapters.push(savedChapter.id)
}
}
module.exports = Book;