Search code examples
node.jsrequireobjection.jsfastify

ObjectionJS - Group models in a data layer file


I have a NodeJS app running fastify with fastify-objectionjs.

For tidiness, I'd like to group all models in a single file called _main.js, where I export an array of the models inside the models folder.

Since the fastify-objectionjs registration requires an array of models, I thought I could just import the array from my _main.js and feed it as it is to the registration function.

But ObjectionJS is telling me that The supplied models are invalid.

/app.js (node entry point)

const fastify = require('fastify')({
    logger: true
})

const knexConfig = require('./knexfile')
const dataLayer = require('./models/_main')
fastify.register(require('fastify-objectionjs'), {
    knexConfig: knexConfig,
    models: dataLayer
})

// Also tried:
// fastify.register(require('fastify-objectionjs'), {
//     knexConfig: knexConfig,
//     models: [dataLayer]
// })

/models/_main.js

const User = require('./user.model')

var dataLayer = [User]

module.exports = dataLayer

// Also tried without var:
// module.exports = {
//     dataLayer: [
//         User
//     ]
// }

/models/user.model.js

const Knex = require('knex')
const connection = require('../knexfile')
const { Model } = require('objection')
const knexConnection = Knex(connection)
Model.knex(knexConnection)

class User extends Model {
  static get tableName () {
    return 'users'
  }
}

module.exports = { User }

I can't seem to find a problem in the file flow, but if I create the models array on the fly, the app starts smoothly:

/app.js (node entry point)

const fastify = require('fastify')({
    logger: true
})

const knexConfig = require('./knexfile')
const User = require('./models/user.model') // changed
fastify.register(require('fastify-objectionjs'), {
    knexConfig: knexConfig,
    models: [User] // changed
})

Any idea why this isn't working? Thanks in advance for your time.


Solution

  • Found the gotcha, I just needed to use destructuring in the require of User, like this:

    /models/_main.js

    // BAD
    // const User = require('./user.model')
    
    // GOOD
    const { User } = require('./user.model')
    
    module.exports = [User]
    

    Works like a charm.

    Useful question that explains the difference: Curly brackets (braces) in node require statement