Search code examples
javascriptnode.jsknex.jsjoi

Knex.js with Joi binding


I'm using Knex.js (along with Bookshelf.js) with a PostreSQL DB and I'm trying to "extract" the SQL schema in order to use it with something like Joi or Checkit.

Here just a simple example:
The schema written with knex:

return knex.schema.createTable('users', table => {
  table.string('username').notNullable()
  table.string('password')
})

And what I would like to automatically get:

const schema = Joi.object().keys({
  username: Joi.string().required(),
  password: Joi.string()
})

The point is simply to avoid writting the schema twice and having a programmatically way to validated the objects, before passing it to bookshelf/knex. Are there any built-ins ways to do it? Or any best practice?


Solution

  • You need to do this manually or write your own schema builder which outputs Joi schema and knex migrations...

    Usually people just make migrations separately in knex and then updates Joi validations to be in sync with changed DB schema.