How do I access Waterline models from grunt tasks?
TL; DR - How to use Waterline models as part of a grunt task in a sail design?
I am trying to create some grunt tasks in a Sails project to process a CSV file and insert data into a Postgres database. I was hoping to use Waterline for this, although it failed to connect to the database.
I was wondering how would I be able to use my Waterline models from a nagging task?
I'm not too sure what Sails is doing behind the scenes to make my models available, although I would be very interested to understand.
I'll clarify in the morning with a sample code of what I've tried.
source to share
I imported things wrong. The following works correctly:
var CWD = process.cwd();
var path = require('path');
var Waterline = require('waterline');
var User = Waterline.Collection.extend(require(path.join(CWD, 'api/models/User')));
module.exports = function (grunt) {
grunt.registerTask('seedDb', 'Given a list of addresses, assign long and lat.', function (clinicCsv, outputCsv) {
// tell grunt this task is async
var done = this.async();
// create ORM
var orm = new Waterline();
orm.loadCollection(User);
// initialize ORM
orm.initialize({
adapters: {
'sails-postgresql': require('sails-postgresql')
},
connections: require(path.join(CWD, 'config/connections')).connections,
defaults: require(path.join(CWD, 'config/models')).models
}, function (err, ontology) {
if (err) throw err;
console.log(ontology.collections);
done();
});
});
};
Where api / models / User:
module.exports = {
identity: 'User',
connection: 'localPostgresqlServer',
attributes: {
firstName: {
type: 'string'
},
lastName: {
type: 'sting'
},
email: {
type: 'email'
},
password: {
type: 'string'
}
}
};
Both config / connections and config / models are in standard Sails format. The key indicated the connection in the model.
source to share
You can also get away with this like this
grunt.registerTask('seedDb', 'Given a list of addresses, assign long and lat.', function (clinicCsv, outputCsv) {
// tell grunt this task is async
var done = this.async();
require('sails').load({
hooks: {
blueprints: false,
controllers: false,
cors: false,
csrf: false,
grunt: false,
i18n: false,
logger: false,
policies: false,
pubsub: false,
request: false,
responses: false,
session: false,
socket: false,
views: false
}
}, function(err, app){
// access to models, do your magic here
done();
});
});
source to share