0

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;
  • 1
    You should declare relations between those two models and then use `await Book.query().insertGraph({title: "My Title", chapters: [{ title: 'FrontMatter' }], author: "My Author"})` coding style you are using above is not something that is very suitable to do with objection. Generally speaking if you are doing queries through multiple models, those probably should go to service layer, but adding helpers to model to do stuff that relates to that single model like even some business related logic could be added directly to models too. Your models are anyways already specific to your business. – Mikael Lepistö Aug 27 '19 at 16:23
  • 2
    So it is more matter of taste than a cold fact that fat models are bad. I didn't write answer, since I didn't want to spend too much time with this. I hope that these comments are somewhat useful though. – Mikael Lepistö Aug 27 '19 at 16:24

0 Answers0