0

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.

GigiSan
  • 1,170
  • 2
  • 19
  • 30
  • @Arfost Do you mean it should be `const dataLayer = require('./models/_main.js')` ? That wouldn't explain why `const User = require('./models/user.model')` works without `.js` in the second example. Anyway, I tried requiring `./models/_main.js` right now and I get the same error. – GigiSan May 28 '19 at 10:54

1 Answers1

0

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

GigiSan
  • 1,170
  • 2
  • 19
  • 30