Tuesday, 4 April 2017

Set waterline model connection globally

I have set up waterline in my project that is not a sails project. I am on version 0.11.x. If I set the connection in each model, it works perfectly. (the commented out line in the first code block)

I have my models working correctly when I set the connection in each model as per the docs:

Waterline = require('waterline');

module.exports = Waterline.Collection.extend({
  tableName: 'external_resource',
  meta: {
    schemaName: 'intellinotedb'
  },
  // connection: 'myLocalPostgres',
  attributes: {
    id: {
      type: 'integer',
      required: true
    },

However, I want to change databases from test to local to prod based on a NODE_ENV var that I set. Is there a place to do this globally for all models? I load all models like this:

models = []
fs.readdirSync(HOMEDIR + '/lib/models/waterline').forEach (file) =>
  models.push(require(HOMEDIR + '/lib/models/waterline/' + file))

class WaterlineORM

  init:(next)=>
    models.forEach (model) ->
      orm.loadCollection(model)

    orm.initialize config, (err, models) =>
      throw err if(err)
      global.models = models.collections
      global.connections = models.connections
      next()

My connections look like this:

const diskAdapter = require('sails-disk');
const postgresAdapter = require('sails-postgresql');

module.exports = {
  adapters: {
    'default': diskAdapter,
    disk: diskAdapter,
    postgres: postgresAdapter
  },

  connections: {
    myLocalDisk: {
      adapter: 'disk',
      migrate: 'alter'
    },

    localhost: {
      migrate: 'safe',
      adapter: 'postgres',
      database: 'intellinote',
      host: 'localhost',
      user: 'postgres',
      password: '',
      port: 5432
    }
  },

  defaults: {

  }
};



via joncodo

No comments:

Post a Comment