hapipal / schwifty

A model layer for hapi integrating Objection ORM

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to use Schwifty models in a seed file?

kevcx2 opened this issue · comments

First off, compliments on all of the excellent hapi pal libraries. I have really enjoyed using them so far. I am hoping to build a simple seed file using my project's Schwifty models. My project is set up according to the hapi pal docs boilerplate.

I can use the knex cli to make a seed file, but am not sure how to use my Schwifty models inside of a knex seed file, and if I just want to do all seeding via Schwifty models, I am not sure I need the knex seed boilerplate.

I attempted to manually create a seed.js file at my project root, trying to access the models from the server object, similar to how I imagine it works with hpal-debug. I was seeing a knex error when attempting to construct a simple query:

const server = require('./server');

server.deployment().then(serverInstance => {
  const models = serverInstance.models()

  const { Users } = models
  const users = Users.query().then(users => {
    console.log(users)
  })
})

resulted in the following error:
Error: no database connection available for a query. You need to bind the model class or the query to a knex instance.

I seem to be missing a step to provide the models with a knex instance, but was thinking that step already happened during the server setup. I can see that the serverInstance object returns a knex instance if I call serverInstance.knex()and returns the expected models if I call serverInstance.models(). I am not sure what the missing step is here?

Glad you've gotten some good use out of the pal libraries! I think the fix here will be simple for you. Schwifty takes care of binding knex to models during server initialization, as described in this section of the API docs. So, my guess is just that you need to initialize your server:

const server = require('./server');

server.deployment()
.then((serverInstance) => {

  return serverInstance.initialize()
    .then(() => serverInstance)
})
.then(serverInstance => {
  const models = serverInstance.models()

  const { Users } = models
  const users = Users.query().then(users => {
    console.log(users)
  })
})

I suggest initializing your server, but as an alternative you can also pass knex to your queries directly, which is a feature of objection:

const server = require('./server');

server.deployment().then(serverInstance => {
  const knex = serverInstance.knex()
  const models = serverInstance.models()

  const { Users } = models
  const users = Users.query(knex).then(users => {
    console.log(users)
  })
})

Thank you! Both options will do the trick.